本文介绍了检查嵌套字典值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于大量嵌套字典,我想检查它们是否包含键.它们中的每一个可能有也可能没有一个嵌套字典,所以如果我在所有这些字典中循环搜索会引发错误:

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"

我目前的解决方案是:

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?

推荐答案

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

Use .get() with empty dictionaries as defaults:

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

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

If the Dict2 key is not present, an empty dictionary is returned, so the next chained .get() will also not find Dict3 and return an empty dictionary in turn. The in test then returns False.

另一种方法是捕获KeyError:

try:
    if 'Dict4' in Dict1['Dict2']['Dict3']:
        print "Yes"
except KeyError:
    print "Definitely no"

这篇关于检查嵌套字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:26