I have a nested OrderedDict that I want to extract from it. But before I can extract this value, I have to make sure that there is a long chain of attributes and that their values ββare nothing.
OrderedDict
What is the most pythonic way to improve 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:
get()
x = data.get('first', {}).get('second', {}).get('third', None)
If at any point the key does not exist, then x = None
x = None
You can surround it in a try / except block as follows:
try: x = data['first']['second']['third'] assert x except KeyError, AssertionError: pass