在嵌套的Python词典中搜索键 [英] Search for a key in a nested Python dictionary

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

问题描述

我有一些这样的Python字典:

I have some Python dictionaries like this:

A = {id: {idnumber: condition},.... 

例如

A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....

我需要搜索字典中是否有任何idnumber == 11,并使用condition进行计算.但是,如果整个字典中没有idnumber == 11,则需要继续使用 next 字典.

I need to search if the dictionary has any idnumber == 11 and calculate something with the condition. But if in the entire dictionary doesn't have any idnumber == 11, I need to continue with the next dictionary.

这是我的尝试:

for id, idnumber in A.iteritems():
    if 11 in idnumber.keys(): 
       calculate = ......
    else:
       break

推荐答案

您已经关闭.

idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
    if idnum in idnumber.keys(): # you can skip '.keys()', it's the default
       calculate = some_function_of(idnumber[idnum])
       break # if we find it we're done looking - leave the loop
    # otherwise we continue to the next dictionary
else:
    # this is the for loop's 'else' clause
    # if we don't find it at all, we end up here
    # because we never broke out of the loop
    calculate = your_default_value
    # or whatever you want to do if you don't find it

如果需要知道内部dict中有多少个11作为键,则可以:

If you need to know how many 11s there are as keys in the inner dicts, you can:

idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())

之所以可行,是因为每个dict中只能有一个密钥,因此您只需测试密钥是否退出即可. in返回等于10TrueFalse,因此sumidnum的出现次数.

This works because a key can only be in each dict once so you just have to test if the key exits. in returns True or False which are equal to 1 and 0, so the sum is the number of occurences of idnum.

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

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