[英]Check if Key Structure exists in Dictionary
我想要一個 function 當給定的鍵列表導致字典中的現有結構時返回 True 。 每個鍵對應字典的深度級別
我遇到的困難是列表的長度(=鍵的數量)和字典的深度都是動態的
#Example Code:
keys1 = ["K1", "K3", "K4"]
keys2 = ["K2", "K6"]
keys3 = ["K1", "K6", "K4"]
dict = {
"K1": {
"K3": {
"K4": "a"
}
},
"K2": {
"K6": "b"
}
}
result = function(keys1, dict) #result should be True
result = function(keys2, dict) #result should be True
result = function(keys3, dict) #result should be False
簡單的遞歸方法:
def function(keys, dct):
return not keys or (keys[0] in dct and function(keys[1:], dct[keys[0]]))
>>> function(keys1, dct) # never shadow built-in names
True
>>> function(keys2, dct)
True
>>> function(keys3, dct)
False
這假設了一個非常統一的結構:所有中間值本身都是字典,並且深度始終至少是鍵的長度。 否則,您將需要處理一些錯誤:
def function(keys, dct):
try:
return not keys or function(keys[1:], dct[keys[0]])
except (TypeError, KeyError): # this allows you to shorten the above
return False
您可以定義遍歷字典的遞歸 function,檢查每個級別是否存在鍵,如果不存在則返回 False,如果鍵列表為空則返回 True。
def function(keys, dictionary):
if len(keys) == 0:
return True
elif keys[0] in dictionary:
return function(keys[1:], dictionary[keys[0]])
else:
return False
(正如 schwobaseggl 在另一個答案中指出的那樣,您不應該隱藏內置名稱dict
。)
這將遍歷所有值並檢查正在使用的值是否是字典:
def function(keys, dictionary):
for value in keys1:
if not isinstance(dictionary,dict) or value not in dictionary:
return False
dictionary = dictionary[value]
return True
一點:不要命名你的變量字典,它與內置類型字典沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.