Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if nested attribute exists

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']
like image 614
Colton Allen Avatar asked Apr 24 '15 19:04

Colton Allen


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

like image 90
MrAlexBailey Avatar answered Nov 15 '22 00:11

MrAlexBailey


You could surround it in a try/except block like so:

try:
    x = data['first']['second']['third']
    assert x
except KeyError, AssertionError:
    pass
like image 21
IcarianComplex Avatar answered Nov 14 '22 23:11

IcarianComplex