简体   繁体   English

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

[英]Search for a key in a nested Python dictionary

I have some Python dictionaries like this: 我有一些像这样的Python词典:

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

eg 例如

A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....

I need to search if the dictionary has any idnumber == 11 and calculate something with the condition . 我需要搜索字典是否有任何idnumber == 11并计算具有condition But if in the entire dictionary doesn't have any idnumber == 11 , I need to continue with the next dictionary. 但如果在整个字典中没有任何idnumber == 11 ,我需要继续下一个字典。

This is my try: 这是我的尝试:

for id, idnumber in A.iteritems():
    if 11 in idnumber.keys(): 
       calculate = ......
    else:
       break

dpath to the rescue. 救援的道路。

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

dpath lets you search by globs, which will get you what you want. 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.

It will iterate out all of the conditions in the dictionary, so no special looping constructs required. 它将迭代字典中的所有条件,因此不需要特殊的循环结构。

See also 也可以看看

You're close. 你很亲密

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

If you need to know how many 11 s there are as keys in the inner dict s, you can: 如果您需要知道内部dict有多少11秒作为键,您可以:

idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())

This works because a key can only be in each dict once so you just have to test if the key exits. 这是有效的,因为一个键只能在每个dict一次,所以你只需要测试键是否退出。 in returns True or False which are equal to 1 and 0 , so the sum is the number of occurences of idnum . in返回TrueFalse ,它们等于10 ,因此sumidnum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM