检查嵌套字典值?

时间:2013-09-02 17:23:22

标签: python dictionary nested

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

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"

但这是令人头痛的,丑陋的,可能不是非常有效的资源。 这是以第一种方式执行此操作的正确方法,但在字典不存在时不会引发错误?

3 个答案:

答案 0 :(得分:40)

.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"

答案 1 :(得分: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

答案 2 :(得分:5)

这是对任意数量的键的推广:

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: Change values in dict of nested dicts using items in a list