Search code examples
pythondictionarynested

Get parents keys from nested dictionary


From the following nested dictionary, how can I get every parent dictionary key of 'value4ac'? By starting the 'value4ac' value, I want to get 'key4', 'key4a', 'Key4ac'.

example_dict = { 'key1' : 'value1',
                 'key2' : 'value2',
                 'key3' : { 'key3a': 'value3a' },
                 'key4' : { 'key4a': { 
                                         'key4aa': 'value4aa',
                                         'key4ab': 'value4ab',
                                         'key4ac': 'value4ac'
                                     },
                            'key4b': 'value4b'
                           }
                   } 

Solution

  • recursion to the rescue!

    example_dict = { 'key1' : 'value1',
                     'key2' : 'value2',
                     'key3' : { 'key3a': 'value3a' },
                     'key4' : { 'key4a': { 'key4aa': 'value4aa',
                                           'key4ab': 'value4ab',
                                           'key4ac': 'value4ac'},
                                'key4b': 'value4b'}
                    }
    
    def find_key(d, value):
        for k,v in d.items():
            if isinstance(v, dict):
                p = find_key(v, value)
                if p:
                    return [k] + p
            elif v == value:
                return [k]
    
    print find_key(example_dict,'value4ac')
    

    how it works

    It looks through the items and checks 2 cases

    • item isn't a dictionary -- In this case, see if it is the value we're looking for. If it is, return a list which contains only the key. (This is our base-case for recursion).
    • item is a dictionary -- Try looking for the key in that dictionary. If it is found in that dictionary (or any sub-dict), return the key which takes the right path pre-pended onto the rest of the path.