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

2024-06-12 17:40:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从嵌套的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

有什么建议吗?


Tags: 字典地方chart密钥名字mydict例子color
3条回答

如果你不知道这把钥匙会在哪一个深度出现,你就需要翻遍整个字典。

我很自由,可以把你的数据转换成一本真正有秩序的字典。如果同一个键出现在不同的子目录中,则该函数可能会产生多个结果:

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)

你在找

print [y[1] for y in mydict[x][i] if y[0] == 'powerpoint_color']

这将筛选要在第一个项中查找powerpoint_color的最深元组,并只保留第二个元组。

试试这个

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

然后。。。

print mydict[1][1][4]['powerpoint_color']

相关问题 更多 >