简体   繁体   English

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

[英]Find a given key's value in a nested ordered dict python

I am trying to find the value of a given key from a nested OrderedDict. 我试图从嵌套的OrderedDict中找到给定键的值。

Key points: 关键点:

  • I don't know how deep this dict will be nested 我不知道这个字典将嵌套多深
  • The name of the key I am looking for is constant, it will be somewhere in the dict 我要查找的密钥的名称是恒定的,它将在字典中的某个位置

I would like to return the value of the key called "powerpoint_color" in this example... 在此示例中,我想返回称为“ 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')]))])),

My initial thought is to do something like this: 我最初的想法是做这样的事情:

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

But I get this error: 但是我得到这个错误:

list indices must be integers, not str

Any advice? 有什么建议吗?

If you don't know at which depth the key will appear, you will need to march through the whole dictionary. 如果您不知道该键将显示在什么深度,则需要遍历整个字典。

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)

Try this 尝试这个

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

Then... 然后...

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

You are looking for 你在找

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

This filters the deepest tuple to look for powerpoint_color in the first item, and keeps only the second one. 这将过滤最深的元组以在第一项中查找powerpoint_color ,而仅保留第二项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM