dict.get(key, default) evaluates default even if key exists

Ethan Furman ethan at stoneleaf.us
Tue Dec 15 16:07:25 EST 2020


On 12/15/20 9:07 AM, Mark Polesky via Python-list wrote:

 > D = {'a':1}
 >
 > def get_default():
 >      print('Nobody expects this')
 >      return 0
 >
 > print(D.get('a', get_default()))

Python has short-circuiting logical operations, so one way to get the behavior you're looking for is:

     D.get('a') or get_default()

--
~Ethan~


More information about the Python-list mailing list