在嵌套的Python字典中搜索一个键

6

我有一些像这样的Python字典:

A = {id: {idnumber: condition},.... 

e.g.

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

参见:https://dev59.com/MWUq5IYBdhLWcg3wNtyB - dreftymac
2个回答

8
dpath 来拯救。

http://github.com/akesterson/dpath-python

可以通过使用通配符进行搜索,从而得到您想要的结果。
$ 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.

它将迭代字典中的所有条件,因此不需要特殊的循环结构。

另请参阅


这是一个经常重复的问题,尽管dpath是一个非常简单明了的解决方案,但它很少得到足够的认可,因此在此提供链接以获得更好的曝光。 - dreftymac

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())

这个方法有效是因为每个字典中只能存在一个键,所以你只需要测试该键是否存在。in命令返回True或False,它们分别等于1和0,所以sum函数的结果就是idnum出现的次数。

嗨@agf,感谢您的帮助。顺便问一下,如果我想数一下idnumber中11的数量应该怎么做呢?谢谢!:) - Alejandro
我不确定你的问题是什么?idnumber是一个dict,而idnum是该dict中的一个键,因此每个idnumber中只能有一个idnum。如果你的意思是拥有11作为键的idnumber字典的总数,我会在我的答案中加上它。 - agf
抱歉,我没有解释清楚。这些字典的方式是,id就像每个idnumber的计数一样,例如:{1: {15: 67.4}, 2: {13: 78.4}, 3: {11 : 723.73}, 4: {11 : 34.21}...所以我需要计算每个字典中所有idnumbers中有多少个11。感谢您的时间! :) - Alejandro
1
@Alejandro 这就是我在回答底部添加的代码所做的。 - agf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接