问题描述
我有一些这样的 Python 词典:
I have some Python dictionaries like this:
A = {id: {idnumber: condition},....
例如
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
我需要搜索字典是否有任何 idnumber == 11
并用 condition
计算一些东西.但是如果在整个字典中没有任何idnumber == 11
,我需要继续next字典.
I need to search if the dictionary has any idnumber == 11
and calculate something with the condition
. But if in the entire dictionary doesn't have any idnumber == 11
, I need to continue with the next dictionary.
这是我的尝试:
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
如果您需要知道内部 dict
中有多少个 11
作为键,您可以:
If you need to know how many 11
s there are as keys in the inner dict
s, you can:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
这是有效的,因为一个键只能在每个 dict
中出现一次,所以您只需要测试该键是否存在.in
返回等于 1
和 0
的 True
或 False
,所以sum
是idnum
出现的次数.
This works because a key can only be in each dict
once so you just have to test if the key exits. in
returns True
or False
which are equal to 1
and 0
, so the sum
is the number of occurences of idnum
.
这篇关于在嵌套的 Python 字典中搜索键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!