繁体   English   中英

Python:检查嵌套字典是否存在

[英]Python : check if the nested dictionary exist

我在列表中有几个嵌套字典,我需要验证是否存在特定路径,例如

dict1['layer1']['layer2'][0]['layer3']

如果路径有效,如何使用 IF 语句检查?

我在想

if dict1['layer1']['layer2'][0]['layer3'] :

但它不起作用

这是带有try/except的显式短代码:

try:
    dict1['layer1']['layer2'][0]['layer3']
except KeyError:
    present = False
else:
    present = True

if present: 
    ...

要获取元素:

try:
    obj = dict1['layer1']['layer2'][0]['layer3']
except KeyError:
    obj = None  # or whatever

据我所知,你必须一步一步走,即:

if 'layer1' in dict1:
   if 'layer2' in dict1['layer1']

等等...

如果你不想走try/except路线,你可以想出一个快速的方法来做到这一点:

def check_dict_path(d, *indices):
    sentinel = object()
    for index in indices:
        d = d.get(index, sentinel)
        if d is sentinel:
            return False
    return True


test_dict = {1: {'blah': {'blob': 4}}}

print check_dict_path(test_dict, 1, 'blah', 'blob') # True
print check_dict_path(test_dict, 1, 'blah', 'rob') # False

如果您还尝试在该位置检索对象(而不仅仅是验证该位置是否存在),这可能是多余的。 如果是这种情况,上述方法可以很容易地相应更新。

这是一个与我推荐的答案类似的问题:

检查python dict中是否存在嵌套键的优雅方法

使用递归函数:

def path_exists(path, dict_obj, index = 0):
    if (type(dict_obj) is dict and path[index] in dict_obj.keys()):
        if (len(path) > (index+1)):
            return path_exists(path, dict_obj[path[index]], index + 1)
        else:
            return True
    else:
        return False

其中 path 是表示嵌套键的字符串列表。

我想提出另一个解决方案,因为我也一直在考虑它。

if not dict1.get("layer1", {}).get("layer2", {})[0].get("layer3", {}):
    ...

dict.get()尝试在每个阶段获取密钥。 如果键不存在,将返回一个空字典,而不是嵌套字典(这是必需的,因为尝试在 None 的默认返回上调用 .get() 将产生AttributeError )。 如果返回为空,它将评估为假。 所以,如果最终结果是一个空的字典,这将不起作用,但如果你能保证结果将被填充,这是一个相当简单的替代方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM