在嵌套的Python字典中搜索密钥

Ale*_*dro 5 python recursion dictionary nested

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

A = {id: {idnumber: condition},.... 
Run Code Online (Sandbox Code Playgroud)

例如

A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
Run Code Online (Sandbox Code Playgroud)

我需要搜索字典中是否有任何字典idnumber == 11并使用condition.但如果在整个字典中没有idnumber == 11,我需要继续下一个字典.

这是我的尝试:

for id, idnumber in A.iteritems():
    if 11 in idnumber.keys(): 
       calculate = ......
    else:
       break
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 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
Run Code Online (Sandbox Code Playgroud)

如果您需要知道11内部dicts中有多少个作为键,则可以:

idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
Run Code Online (Sandbox Code Playgroud)

之所以可行,是因为每个密钥只能进入dict一次,因此您只需测试密钥是否退出即可。in返回TrueFalse等于10,因此sum是的出现次数idnum


小智 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.
Run Code Online (Sandbox Code Playgroud)

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

也可以看看


归档时间:

查看次数:

8655 次

最近记录:

7 年,11 月 前