在嵌套的Python字典中搜索键

2024-05-16 06:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

例如

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

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

这是我的尝试:

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

Tags: inid内容forif字典keyscondition
2条回答

你很接近。

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键,可以:

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

这是因为密钥只能在每个dict中出现一次,所以您只需测试密钥是否存在。in返回TrueFalse,等于10,因此sumidnum的出现次数。

相关问题 更多 >