Extracting the keys associated in previous levels nested dictionary

大憨熊 提交于 2019-12-07 11:24:19

问题


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


回答1:


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']
[]


来源:https://stackoverflow.com/questions/53439528/extracting-the-keys-associated-in-previous-levels-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!