Why is the default in dict.get(key[, default])
evaluated even if the key is in the dictionary?
>>> key = 'foo' >>> a={} >>> b={key:'bar'} >>> b.get(key, a[key]) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> b.get(key, a[key]) KeyError: 'foo'
As in any function call, the arguments are evaluated before the call is executed.
In this case dict.get()
is no exception...
use this instead
x = b.get(key) or a.get(key)
or
and and
are short circuit operators, so if b
has the key it won't look at a
. But problems will arise if you have false
values in b
. If that is the case you can do:
x = b[key] if key in b else a.get(key)
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