我在列表中有几个嵌套字典,我需要验证是否存在特定路径Python:检查嵌套字典是否存在
dict1['layer1']['layer2'][0]['layer3']
我如何使用IF语句检查路径是否有效?
我当时就想,
if dict1['layer1']['layer2'][0]['layer3'] :
,但它不工作
我在列表中有几个嵌套字典,我需要验证是否存在特定路径Python:检查嵌套字典是否存在
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']
ANS等等......
如果你不想去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
这可能是多余的,如果你也试图检索该位置的对象(而不是只是验证该位置是否存在)。如果是这样的话,上述方法可以很容易地相应地更新。
一种方式是[请求原谅(http://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain)而不是测试它的存在。 – roganjosh
所以,你试着按照这条路径,假设它总是存在,当它不存在时,除外。 – ForceBru
我尝试在变量中分配路径中的值,但未能返回错误(KeyError:'media') –