Cua
Cua

Reputation: 137

Extracting the keys associated in previous levels nested dictionary

I have a large nested dictionary with an unknown depth and i would like to know how i can find the keys which led to the value. For example...

{'furniture':{'chair':{'sofa':{'cushion':{}}}}}

Ideally what i am looking for is a function to determine the path to the value that i have entered. I have tried researching online and this is what i tried...

def route(d,key):
    if key in d: return d[key]

    for k,v in d.items():
        if isinstance(v,dict):
            item = route(v, key)
            if item is not None:
                return item

This returns the items inside the key. I am looking to be able to extract the path which leads to that item. For example, route(dictionary,'sofa') then i would be able to get an expected output as such or something similar...

{'sofa':{'chair':'furniture'}}

What are some of the ways that i can achieve this ? Thanks for your help

Upvotes: 4

Views: 243

Answers (1)

slider
slider

Reputation: 12990

You can do this recursively and return a list of keys that lead you to your target key:

def route(d, key):
    if key in d: return [key]
    for k, v in d.items():
        if type(v) == dict:
            found = route(v, key)
            if found: return [k] + found
    return []

If we run this on the following dictionary:

data = {
    'furniture': {
        'chair': {
            'sofa': {
                'cushion': {}
            }
        }
    },
    'electronics': {
        'tv': {
            'samsung43': 800,
            'tcl54': 200
        }
    }
}

print(route(data, 'cushion'))
print(route(data, 'tcl54'))
print(route(data, 'hello'))

we get the following output:

['furniture', 'chair', 'sofa', 'cushion']
['electronics', 'tv', 'tcl54']
[]

Upvotes: 3

Related Questions