我有一些像这样的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
答案 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
返回True
或False
,其等于1
和0
,因此sum
是idnum
的出现次数}。
答案 1 :(得分:5)
http://github.com/akesterson/dpath-python
dpath让你通过globs进行搜索,这将为你提供你想要的东西。
$ easy_install dpath
>>> for (path, value) in dpath.util.search(MY_DICT, '*/11', yielded=True):
>>> ... # 'value' will contain your condition; now do something with it.
它将迭代字典中的所有条件,因此不需要特殊的循环结构。