Is there a clear best practice for assigning a variable from a key/value pair in a Python dictionary:
- If the key is present
- If the key’s value is not an empty string
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?
Maybe you mean something like:
which I think should be equivalent to the
if-elseconditional you havee.g.
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
orshort circuits (As soon as it hits aTruelike value, it returns it. If no True-like value is found,orreturns 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 offunc.