【发布时间】:2021-02-13 02:02:55
【问题描述】:
我有一个嵌套字典,我正在尝试编写一个函数来查找匹配的键,并将路径中的所有键返回到匹配的键。给定下面的示例嵌套字典:
nested_dict = {'a': {'b':{'c': 'd',
'e': 'f'},
'g': {'h': {'i': 'j'}}},
'k': {'l': 'm',
'n': 'o',
'p': {'q': 'r',
's': 't'}}}
我希望函数 getpath 返回:
getpath(s) = ['k','p','s']
getpath(i) = ['a', 'g','h','i']
我写了下面的递归函数来尝试完成这个,但它没有返回任何东西,我希望我很接近但我犯了一个小错误:
start_keys = list()
def getpath(nested_dict,search_value,keys):
# extract keys from the dict
dict_keys = list(nested_dict.keys())
# loop through dict keys
for key in dict_keys:
# append key to keys
keys.append(key)
level_down = nested_dict[key]
# check if the key matches the target value
if search_value.lower()==key.lower():
# if it does match, we're good, so return keys
return(keys)
else:
# since it didn't match, we attempt to go further down
if type(level_down) is dict:
# run getpath on it
getpath(level_down, search_value, keys)
else:
# if we can't go further down, it means we got to the end without finding a match, so we wipe out keys
keys = list()
【问题讨论】:
标签: python json dictionary recursion nested