在嵌套的有序字典 python 中查找给定键的值 [英] Find a given key's value in a nested ordered dict python

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

问题描述

我试图从嵌套的 OrderedDict 中找到给定键的值.

I am trying to find the value of a given key from a nested OrderedDict.

要点:

  • 我不知道这个 dict 会嵌套多深
  • 我要查找的密钥的名称是不变的,它将在字典中的某个位置

我想返回本例中名为powerpoint_color"的键的值...

I would like to return the value of the key called "powerpoint_color" in this example...

mydict= OrderedDict([('KYS_Q1AA_YouthSportsTrustSportParents_P',
                      OrderedDict([('KYS_Q1AA',
                                    OrderedDict([('chart_layout', '3'),
                                                 ('client_name', 'Sport Parents (Regrouped)'),
                                                 ('sort_order', 'asending'),
                                                 ('chart_type', 'pie'),
                                                 ('powerpoint_color', 'blue'),
                                                 ('crossbreak', 'Total')]))])),

我最初的想法是做这样的事情:

My initial thought is to do something like this:

print mydict[x][i]['powerpoint_color']

但我收到此错误:

list indices must be integers, not str

有什么建议吗?

推荐答案

如果你不知道key会出现在哪个深度,你需要遍历整个字典.

If you don't know at which depth the key will appear, you will need to march through the whole dictionary.

我可以自由地将您的数据转换为实际的有序字典.同一个key出现在不同子目录的情况下,函数可能会产生多个结果:

I was so free as to convert your data to an actual ordered dictionary. The function may yield more than one result in the case that the same key appears in different sub-directories:

from collections import OrderedDict

mydict = OrderedDict ( {'KYS_Q1AA_YouthSportsTrustSportParents_P':
            OrderedDict ( {'KYS_Q1AA':
                OrderedDict ( [ ('chart_layout', '3'),
                 ('client_name', 'Sport Parents (Regrouped)'),
                 ('sort_order', 'asending'),
                 ('chart_type', 'pie'),
                 ('powerpoint_color', 'blue'),
                 ('crossbreak', 'Total')
                 ] ) } ) } )

def listRecursive (d, key):
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for found in listRecursive (v, key):
                yield found
        if k == key:
            yield v

for found in listRecursive (mydict, 'powerpoint_color'):
    print (found)

<小时>

如果您对找到密钥的位置感兴趣,可以相应地调整代码:


If you are interested in where you have found the key, you can adapt the code accordingly:

def listRecursive (d, key, path = None):
    if not path: path = []
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for path, found in listRecursive (v, key, path + [k] ):
                yield path, found
        if k == key:
            yield path + [k], v

for path, found in listRecursive (mydict, 'powerpoint_color'):
    print (path, found)

这篇关于在嵌套的有序字典 python 中查找给定键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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