我在列表中有幾個嵌套字典,我需要驗證是否存在特定路徑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') –