提取上一级嵌套字典中关联的键 [英] Extracting the keys associated in previous levels nested dictionary

查看:109
本文介绍了提取上一级嵌套字典中关联的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本深度未知的大型嵌套字典,我想知道如何找到导致该值的键.例如...

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

这将返回键内的项目.我希望能够提取导致该项目的路径.例如,route(dictionary,'sofa'),那么我将能够获得预期的输出或类似的结果...

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

推荐答案

您可以递归执行此操作,并返回将您引向目标键的键列表:

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'))

我们得到以下输出:

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

这篇关于提取上一级嵌套字典中关联的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆