Check for a nested attribute

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.

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'] 
+5
source share
2 answers

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

+7
source

You can surround it in a try / except block as follows:

 try: x = data['first']['second']['third'] assert x except KeyError, AssertionError: pass 
+2
source

All Articles