如何获取嵌套字典中值为'here'的嵌套路径字典列表
解决方案
你可以通过两种方式实现需求:基于现有路径列表转换为嵌套字典,或者直接修改递归函数生成目标结构。
方法一:路径列表转嵌套字典
利用你已实现的路径列表生成逻辑,新增辅助函数将路径列表转换为嵌套字典结构:
def path_to_nested_dict(path): # 从路径终点开始向上构建嵌套字典 current = path[-1] # 反向遍历路径的前n-1个元素 for key in reversed(path[:-1]): current = {key: current} return current # 你原有的路径生成函数 def find_word(dictionary, path=[]): results = [] for key, value in dictionary.items(): new_path = path + [key] if isinstance(value, dict): results.extend(find_word(value, new_path)) elif value == 'here': results.append(new_path) return results # 示例使用 d = {'a': {'b': {'c': 'here', 'd': 'here'}}, 'e': {'f': 'here'}} paths = find_word(d) nested_results = [path_to_nested_dict(p) for p in paths] print(nested_results)
输出:
[{'a': {'b': 'c'}}, {'a': {'b': 'd'}}, {'e': 'f'}]
方法二:直接递归生成嵌套字典
修改递归逻辑,在遍历过程中直接构建嵌套字典,无需生成中间路径列表:
def find_word_nested(dictionary): results = [] for key, value in dictionary.items(): if isinstance(value, dict): # 递归处理子字典,获取子路径结构 sub_results = find_word_nested(value) # 将当前key与子结构组合为新的嵌套字典 for sub in sub_results: results.append({key: sub}) elif value == 'here': # 找到目标值,将当前key作为路径终点 results.append(key) return results # 示例使用 d = {'a': {'b': {'c': 'here', 'd': 'here'}}, 'e': {'f': 'here'}} print(find_word_nested(d))
输出符合预期:
[{'a': {'b': 'c'}}, {'a': {'b': 'd'}}, {'e': 'f'}]
内容的提问来源于stack exchange,提问作者gioarma
相关产品推荐
相关产品推荐

