你近了
idnum = 11# The loop and 'if' are good# You just had the 'break' in the wrong placefor 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 dictionaryelse: # 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内部
dicts中有多少个作为键,则可以:
idnum = 11print sum(idnum in idnumber for idnumber in A.itervalues())
之所以可行,是因为每个密钥只能进入
dict一次,因此您只需测试密钥是否退出即可。
in返回
True或
False等于
1和
0,因此
sum是的出现次数
idnum。



