Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean test for a dictionary element in Python?

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']
like image 845
Jeanne Lane Avatar asked Jan 09 '17 17:01

Jeanne Lane


1 Answers

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.

like image 93
Willem Van Onsem Avatar answered Sep 27 '22 15:09

Willem Van Onsem