如何动态获取嵌套字典中最深层非字典值的键路径列表
提取嵌套字典的所有非字典值键路径
递归实现方案
递归遍历字典时,通过创建新的路径列表而非修改原列表来避免路径回溯问题,确保每个层级的路径独立正确。
def get_key_paths(nested_dict): paths = [] def traverse(current_dict, current_path): for key, value in current_dict.items(): if isinstance(value, dict): # 递归时传递新路径(当前路径 + 新键),不修改原路径 traverse(value, current_path + [key]) else: # 非字典值,记录完整路径 paths.append(current_path + [key]) traverse(nested_dict, []) return paths
测试示例
sample_dict = { "parent": { "a": 1, "b": { "nested": "first" } } } # 获取键路径列表 key_paths = get_key_paths(sample_dict) print(key_paths) # 输出: [['parent', 'a'], ['parent', 'b', 'nested']]
配合functools.reduce提取值构建新字典
使用reduce和operator.getitem可以快速根据路径从嵌套字典中取值,以下是两种常见的构建新字典的方式:
1. 扁平化键名的新字典
from functools import reduce import operator def get_value_from_path(data, path): # 用reduce逐层获取嵌套值 return reduce(operator.getitem, path, data) # 构建扁平化键的字典 flat_dict = {} for path in key_paths: flat_key = ".".join(path) flat_dict[flat_key] = get_value_from_path(sample_dict, path) print(flat_dict) # 输出: {'parent.a': 1, 'parent.b.nested': 'first'}
2. 保持嵌套结构的新字典
def build_nested_result(paths, source_data): result = {} for path in paths: current_layer = result # 遍历路径的前n-1个键,创建嵌套结构 for key in path[:-1]: if key not in current_layer: current_layer[key] = {} current_layer = current_layer[key] # 赋值最后一个键对应的值 current_layer[path[-1]] = get_value_from_path(source_data, path) return result nested_result = build_nested_result(key_paths, sample_dict) print(nested_result) # 输出: {'parent': {'a': 1, 'b': {'nested': 'first'}}}
内容的提问来源于stack exchange,提问作者alpacafondue
相关产品推荐
相关产品推荐

