我想要一个当给定的键列表导致字典中现有结构返回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
答案 0 :(得分:4)
简单的递归方法:
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
答案 1 :(得分:3)
您可以定义一个遍历字典的递归函数,检查键是否在每个级别上存在,如果不存在则返回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
。)
答案 2 :(得分:2)
这会遍历所有值并检查使用的值是否是字典:
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
一点:不要命名您的变量dict,它与内置类型dict冲突。