检查嵌套字典的值?

2024-09-28 20:53:27 发布

您现在位置:Python中文网/ 问答频道 /正文

对于嵌套字典的大列表,我想检查它们是否包含键。 它们中的每一个都可能有或没有一个嵌套字典,因此,如果我在所有这些字典中循环此搜索,将引发一个错误:

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"

但这是一个头痛,丑陋,可能不是很有效的资源。 在第一种类型的方式下,哪种方法是正确的,但是在字典不存在时不会产生错误?


Tags: in列表forif字典错误解决方案yes
3条回答

尝试/排除块怎么样:

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

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

以下是任意键数的一般化:

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

相关问题 更多 >