在嵌套的Python字典中搜索密钥

时间:2011-10-06 22:42:12

标签: python dictionary recursion nested

我有一些像这样的Python词典:

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

e.g。

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

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

这是我的尝试:

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

2 个答案:

答案 0 :(得分:5)

你很亲密。

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

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

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

这是有效的,因为密钥只能在每个dict中一次,因此您只需要测试密钥是否退出。 in返回TrueFalse,其等于10,因此sumidnum的出现次数}。

答案 1 :(得分:5)