Is there a clear best practice for assigning a variable from a key/value pair in a Python dictionary:
And otherwise assigning a default value to the variable.
I would like to use dict.get
:
my_value = dict.get(key, my_default)
But this assigns an empty string to my_value
if the key is present and the value is an empty string. Is it better to use the following:
if key in dict and dict[key]: my_value = dict[key] else: my_value = my_default
This would make use of the truthfulness of an empty string to ensure only non-empty strings were assigned to my_value
.
Is there a better way to perform this check?
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
Check if a Python Dictionary is Empty by Checking Its Lengthif len(empty_dict) == 0: print('This dictionary is empty! ')
Maybe you mean something like:
a.get('foo',my_default) or my_default
which I think should be equivalent to the if-else
conditional you have
e.g.
>>> a = {'foo':''} >>> a.get('foo','bar') or 'bar' 'bar' >>> a['foo'] = 'baz' >>> a.get('foo','bar') or 'bar' 'baz' >>> a.get('qux','bar') or 'bar' 'bar'
The advantages to this over the other version are pretty clear. This is nice because you only need to perform the lookup once and because or
short circuits (As soon as it hits a True
like value, it returns it. If no True-like value is found, or
returns the second one).
If your default is a function, it could be called twice if you write it as: d.get('foo',func()) or func()
. In this case, you're better off with a temporary variable to hold the return value of func
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With