13

For a large list of nested dictionaries, I want to check if they contain or not a key. Each of them may or may not have one of the nested dictionaries, so if I loop this search through all of them raises an error:

for Dict1 in DictionariesList:
     if "Dict4" in Dict1['Dict2']['Dict3']:
         print "Yes"

My solution so far is:

for Dict1 in DictionariesList:    
    if "Dict2" in Dict1:
        if "Dict3" in Dict1['Dict2']:
            if "Dict4" in Dict1['Dict2']['Dict3']:
                print "Yes"

But this is a headache, ugly, and probably not very resources effective. Which would be the correct way to do this in the first type fashion, but without raising an error when the dictionary doesnt exist?

4

3 回答 3

42

使用.get()空字典作为默认值:

if 'Dict4' in Dict1.get('Dict2', {}).get('Dict3', {}):
    print "Yes"

如果Dict2键不存在,则返回一个空字典,因此下一个链式.get()也将找不到Dict3并依次返回一个空字典。然后in测试返回False

另一种方法是抓住KeyError

try:
    if 'Dict4' in Dict1['Dict2']['Dict3']:
        print "Yes"
except KeyError:
    print "Definitely no"
于 2013-09-02T17:25:10.393 回答
8

try/except 块怎么样:

for Dict1 in DictionariesList:
    try:
        if 'Dict4' in Dict1['Dict2']['Dict3']:
            print 'Yes'
    except KeyError:
        continue # I just chose to continue.  You can do anything here though
于 2013-09-02T17:27:17.417 回答
6

这是任意数量的键的概括:

for Dict1 in DictionariesList:
    try: # try to get the value
        reduce(dict.__getitem__, ["Dict2", "Dict3", "Dict4"], Dict1)
    except KeyError: # failed
        continue # try the next dict
    else: # success
        print("Yes")

基于Python:使用列表中的项目更改嵌套字典的字典中的值

于 2013-09-02T17:34:28.617 回答