Is there any difference, gotcha or disadvantage between these approaches?
foo = dict(key=u"")
bar = foo.get('key', 'foobar')
vs
foo = dict(key=u"")
bar = bool(foo['key']) or 'foobar'
You should most definitely not use the second form, because it will throw a KeyError
if the key does not exist your dictionary. You're only getting acceptable behavior out of the second form because the key was set.
The first piece of code tries to get a value from foo
associated with key
, and if foo
does not have the key key
, defaults to foobar
. So there are two cases here:
foo
has the key key
, so bar
is set to foo[key]
foo
does not have the key key
, so bar
is set to "foobar"
The second looks at the value associated with the key key
in foo
, and if that value is falsy (that is, if bool(foo[key])==False
), it defaults to foobar
. If foo
does not have the key key
it raises a KeyError
. So there are three cases here:
foo
has the key key
, and bool(foo[key])==True
, so bar
is set to True
foo
has the key key
, and bool(foo[key])==False
, so bar
is set to "foobar"
foo
does not have the key key
, so the code raises a KeyError
The 2nd example will raise KeyError
if foo['key']
doesn't exist.
If you want to assign a default value to bar
if foo['key']
doesn't exist or contains falsey value, this would be the Pythonic way to do it:
bar = foo.get('key') or 'foobar'
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