I have a nested OrderedDict
that I want to extract a value out of. But before I can extract that value I have to make sure a long chain of attributes exist and that their values aren't none.
What is the most pythonic way of improving the following code:
if 'first' in data and \
data['first'] and \
'second' in data['first'] and \
data['first']['second'] and \
'third' in data['first']['second'] and \
data['first']['second']['third']:
x = data['first']['second']['third']
Another route would be to use the get()
method:
x = data.get('first', {}).get('second', {}).get('third', None)
If at any point the key does not exist, then x = None
You could surround it in a try/except block like so:
try:
x = data['first']['second']['third']
assert x
except KeyError, AssertionError:
pass
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