在嵌套有序字典 python 中查找给定键的值

2024-04-30

我试图从嵌套的 OrderedDict 中查找给定键的值。

关键点:

  • 我不知道这个字典会嵌套多深
  • 我正在寻找的键的名称是不变的,它将位于字典中的某个位置

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

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

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

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

但我收到这个错误:

list indices must be integers, not str

有什么建议吗?


如果您不知道键将出现在哪个深度,则需要遍历整个字典。

我很自由,可以将您的数据转换为实际有序的字典。如果相同的键出现在不同的子目录中,该函数可能会产生多个结果:

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)

如果您对在哪里找到密钥感兴趣,可以相应地调整代码:

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在嵌套有序字典 python 中查找给定键的值 的相关文章