Skip to main content
 首页 » 编程设计

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

2025年05月04日14lonelyxmas

我正在尝试从嵌套的 OrderedDict 中查找给定键的值。

要点:

  • 不知道这个dict会嵌套多深
  • 我要找的key的名字是常量,它会在dict的某个地方

在此示例中,我想返回名为“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) 

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

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)