Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionaries, key existence with fallback [closed]

Tags:

python

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'
like image 576
Hedde van der Heide Avatar asked Aug 15 '12 14:08

Hedde van der Heide


3 Answers

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.

like image 52
g.d.d.c Avatar answered Oct 29 '22 14:10

g.d.d.c


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:

  1. foo has the key key, so bar is set to foo[key]
  2. 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:

  1. foo has the key key, and bool(foo[key])==True, so bar is set to True
  2. foo has the key key, and bool(foo[key])==False, so bar is set to "foobar"
  3. foo does not have the key key, so the code raises a KeyError
like image 30
murgatroid99 Avatar answered Oct 29 '22 14:10

murgatroid99


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'
like image 43
Imran Avatar answered Oct 29 '22 14:10

Imran