在嵌套的有序词典python中查找给定键的值 [英] Find a given key's value in a nested ordered dict python

查看:166
本文介绍了在嵌套的有序词典python中查找给定键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



要点:$ b​​
$ b


  • 我不知道这个字典有多深被嵌套

  • 我正在寻找的密钥的名称是不变的,它将在字典中的某处



我想返回在这个例子中名为powerpoint_color的键的值...

  mydict = OrderedDict([('KYS_Q1AA_YouthSportsTrustSportParents_P',
OrderedDict([('KYS_Q1AA',
OrderedDict([('chart_layout','3'),
('client_name','Sport Parents (重新分组)'),
('sort_order','asending'),
('chart_type','pie'),
('powerpoint_color','blue'),
('cros sbreak','Total')]))])),

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

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



但是我得到这个错误:

  list索引必须是整数,而不是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在d.items()中:
如果isinstance(v,OrderedDict):
在listRecursive(v,key)中找到:
找到收益
if k == key :
产生v

在listRecursive中找到(mydict,'powerpoint_color'):
打印(找到)






如果您对您找到钥匙的位置感兴趣,可以相应地调整代码:

  def listRecursive(d,key,path = None):
if not path:path = []
for k,v in d.items():
如果isinstance(v,OrderedDict):
for path,在listRecursive(v,key,path + [k])中找到:
yield path,找到
if k == key:
yield path + [k] ,v

for path,在listRecursive(mydict,'powerpoint_color')中找到:
print(path,found)


I am trying to find the value of a given key from a nested 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...

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)

这篇关于在嵌套的有序词典python中查找给定键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆