在嵌套Python字典中搜索关键字
我有一些Python字典,如下所示:在嵌套Python字典中搜索关键字,python,dictionary,recursion,nested,Python,Dictionary,Recursion,Nested,我有一些Python字典,如下所示: A = {id: {idnumber: condition},.... e、 g 我需要搜索字典是否有idnumber==11,并使用条件计算一些内容。但是如果在整个字典中没有任何idnumber==11,我需要继续使用下一个字典 这是我的尝试: for id, idnumber in A.iteritems(): if 11 in idnumber.keys(): calculate = ...... else:
A = {id: {idnumber: condition},....
e、 g
我需要搜索字典是否有idnumber==11
,并使用条件计算一些内容。但是如果在整个字典中没有任何idnumber==11
,我需要继续使用下一个字典
这是我的尝试:
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
s中有多少个11
s作为键,您可以:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
这是因为一个键只能在每个dict
中存在一次,所以您只需测试该键是否存在in
返回True
或False
,它们等于1
和0
,因此sum
是idnum救援路径的发生次数。
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.
它将迭代字典中的所有条件,因此不需要特殊的循环构造
另见
hi@agf谢谢你的帮助。顺便说一句,如果我想数一数idnumber中的11,我该怎么做??谢谢!!!:)我不确定你的问题是什么idnumber
是一个dict
,而idnum
是该dict
中的一个键,因此每个idnumber
中只能有一个idnum
。如果您指的是以11
s作为键的idnumber
dict的总数,我会将其添加到我的答案中。对不起,我没有正确解释。这些字典在某种程度上,id就像是每个idnumber的计数,也就是说,像这样{1:{15:67.4},2:{13:78.4},3:{11:723.73},4:{11:34.21}…
因此,我需要计算每个dict中的所有IDNumber中有多少个11。感谢您的时间!!!:)@Alejandro这就是我添加到我答案底部的代码所做的。这是一个普遍存在的重复问题,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.