检查嵌套字典值?

I w*_*ges 12 python dictionary nested

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

for Dict1 in DictionariesList:
     if "Dict4" in Dict1['Dict2']['Dict3']:
         print "Yes"
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案是:

for Dict1 in DictionariesList:    
    if "Dict2" in Dict1:
        if "Dict3" in Dict1['Dict2']:
            if "Dict4" in Dict1['Dict2']['Dict3']:
                print "Yes"
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 40

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

if 'Dict4' in Dict1.get('Dict2', {}).get('Dict3', {}):
    print "Yes"
Run Code Online (Sandbox Code Playgroud)

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

另一种方法是抓住KeyError:

try:
    if 'Dict4' in Dict1['Dict2']['Dict3']:
        print "Yes"
except KeyError:
    print "Definitely no"
Run Code Online (Sandbox Code Playgroud)

  • 惊人的,经过测试和工作,非常感谢.会尽快接受.你真的是一个忍者. (2认同)
  • 如果链中有任何"无"值键,则第一个提议将失败.例如,测试不适用于`Dict1 = {'Dict2':无}`.因此,捕获异常似乎是最干净的解决方案. (2认同)

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


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

基于Python:使用列表中的项目更改嵌套dicts的dict中的值.