Extracting the keys associated in previous levels nested dictionary

喜夏-厌秋 提交于 2019-12-05 15:58:43

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