Reputation: 21243
I am working in python, and was using dict
in my code.
I have case where I always need default
value if the give key
is not exist or if key
exists and it has falsy
value.
for example
x = {'a': 'test', 'b': False, 'c': None, 'd': ''}
print x.get('a', [])
test
print x.get('b', []) # Need [] as False is falsy value in python
False
print x.get('e', []) # This will work fine, because `e` is not valid key
None
print x.get('c', [])
None
print x.get('c', []) or [] # This gives output which I want
Instead of check Falsy
value in or
operation, is there any pythonic way to get my default value?
Upvotes: 2
Views: 1412
Reputation: 3775
Here is an ugly hack:
from collections import defaultdict
x = {'a': 'test', 'b': False, 'c': None, 'd': ''}
d = defaultdict(lambda : [], dict((k, v) if v is not None else (k, []) for k, v in x.items()))
print(d['a'])
# test
print(d['b'])
# False
print(d['e'])
# []
print(d['c'])
# []
Upvotes: 0
Reputation: 78546
Using or
to return your default value is Pythonic. I'm not sure you will get a more readable workaround.
About using or
in the docs:
This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
You must also consider that the value must have been accessed first before it can then be evaluated as Falsy or Truthy.
Upvotes: 4