python - Get default value if key has falsy value in dict -


i working in python, , using dict in code.

i have case need default value if give key not exist or if key exists , has falsy value.

for example

x = {'a': 'test', 'b': false, 'c': none, 'd': ''} print x.get('a', []) test print x.get('b', []) # need [] false falsy value in python false  print x.get('e', []) # work fine, because `e` not valid key none print x.get('c', [])  none print x.get('c', []) or [] # gives output want 

instead of check falsy value in or operation, there pythonic way default value?

using or return default value pythonic. i'm not sure more readable workaround.

about using or in docs:

this short-circuit operator, evaluates second argument if first 1 false.

you must consider value must have been accessed first before can evaluated falsy or truthy.


Comments