我有一些这样的Python字典:
A = {id: {idnumber: condition},....
例如
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
我需要搜索字典中是否有字典,idnumber == 11并使用来计算condition。但是,如果整个字典中没有任何字典idnumber == 11,则需要继续 下一个 字典。
idnumber == 11
condition
这是我的尝试:
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
如果您需要知道11内部dicts中有多少个作为键,则可以:
11
dict
idnum = 11 print sum(idnum in idnumber for idnumber in A.itervalues())
之所以可行,是因为每个密钥只能进入dict一次,因此您只需测试密钥是否退出即可。in返回True或False等于1和0,因此sum是的出现次数idnum。
in
True
False
1
0
sum
idnum