gpt4 book ai didi

python - 检查字典中是否存在键结构

转载 作者:行者123 更新时间:2023-12-04 22:54:25 27 4
gpt4 key购买 nike

我想要一个函数,当给定的键列表导致字典中的现有结构时,该函数返回 True。每个key对应字典的深度级别

我遇到的困难是列表的长度(= 键的数量)和字典的深度都是动态的

#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

关于python - 检查字典中是否存在键结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58322197/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com