Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dict.get() - default arg evaluated even upon success

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' 
like image 471
Jonathan Livni Avatar asked Mar 18 '12 19:03

Jonathan Livni


2 Answers

As in any function call, the arguments are evaluated before the call is executed.
In this case dict.get() is no exception...

like image 92
Jonathan Livni Avatar answered Sep 18 '22 21:09

Jonathan Livni


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) 
like image 40
Doboy Avatar answered Sep 19 '22 21:09

Doboy