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

问题描述 投票:1回答:3

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

关键点:

  • 我不知道这个dict有多深
  • 我正在寻找的密钥的名称是不变的,它将在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

有什么建议?

python get find key-value ordereddictionary
3个回答
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)

3
投票

试试这个

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

1
投票

你在找

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

这会过滤最深的元组,在第一项中查找powerpoint_color,并仅保留第二项。

© www.soinside.com 2019 - 2024. All rights reserved.