If I have an element I'm trying to get from a dictionary:
my_dict[i]['level_1']['level_2']['my_var']
.
Is there a cleaner way than doing this to check for nulls?
if 'level_1' in my_dict[i]:
if 'level_2' in my_dict[i]['level_1']:
if 'my_var' in my_dict[i]['level_1']['level_2']:
my_var = my_dict[i]['level_1']['level_2']['my_var']
You can simply define your own:
def get_deep(dic,*keys,default=None):
for key in keys:
if isinstance(dic,dict) and key in dic:
dic = dic[key]
else:
return default
return dic
Or if you want to test:
def in_deep(dic,*keys):
for key in keys:
if isinstance(dic,dict) and key in dic:
dic = dic[key]
else:
return False
return True
You can use this code with in_deep(my_dict[i],'level1','level2','my_var')
and it will return True
if it can indeed get that deep in the dictionary. If you want to obtain the element that deep, you can call get_deep(my_dict[i],'level1','level2','my_var')
. get_deep
will return the default
parameter (by default None
) in case it cannot reach the path.
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