在嵌套的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
2 个回答
8
dpath来帮忙。
http://github.com/akesterson/dpath-python
dpath可以让你通过通配符来搜索,这样你就能找到你想要的东西。
$ 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.
它会遍历字典中的所有条件,所以你不需要特别复杂的循环结构。
相关内容
7
你离答案很近。
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
如果你想知道在内部的 dict
中,有多少个 11
作为键,你可以这样做:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
这样做是有效的,因为一个键在每个 dict
中只能出现一次,所以你只需要检查这个键是否存在。in
会返回 True
或 False
,分别代表 1
和 0
,所以用 sum
就可以得到 idnum
出现的次数。