I have a dictionary which may or may not have one or both keys 'foo' and 'bar'. Depending on whether both or either are available, I need to do different things. Here is what I am doing (and it works):
foo = None
bar = None
if 'foo' in data:
if data['foo']:
foo = data['foo']
if 'bar' in data:
if data['bar']:
bar = data['bar']
if foo is not None and bar is not None:
dofoobar()
elif foo is not None:
dofoo()
elif bar is not None:
dobar()
This seems too verbose - what is the idiomatic way to do this in Python (2.7.10)?
You can use dict.get()
to shorten your code. Rather than raising a KeyError
when a key is not present, None
is returned:
foo = data.get('foo')
bar = data.get('email')
if foo is not None and bar is not None:
dofoobar()
elif foo is not None:
dofoo()
elif bar is not None:
dobar()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With