Python中如何将嵌套字典转换为每行对应分支路径的表格
嵌套字典转分支表格解决方案
实现思路
通过递归遍历所有根节点到叶子节点的路径,每一条路径对应表格的一行,路径上的各级键以及最终叶子节点的值按顺序组成行的字段。
实现代码
1. 核心路径提取函数
def extract_tree_paths(tree, current_path=None): if current_path is None: current_path = [] for key, value in tree.items(): new_path = current_path + [key] if isinstance(value, dict): yield from extract_tree_paths(value, new_path) else: yield new_path + [value]
2. 调用示例
# 你的嵌套字典数据 data = { "A1": { "A1-1": { "A1-1-1": "0.2028", "A1-1-2": "0.1901", }, "A1-2": { "A1-2-1": "0.1951", "A1-2-2": "0.1806", }, } } # 生成所有行数据 rows = list(extract_tree_paths(data)) # 转换为DataFrame表格 import pandas as pd df = pd.DataFrame(rows) # 输出查看结果 print(df.to_string(header=False, index=False))
输出结果
A1 A1-1 A1-1-1 0.2028 A1 A1-1 A1-1-2 0.1901 A1 A1-2 A1-2-1 0.1951 A1 A1-2 A1-2-2 0.1806
原方法问题说明
json_normalize的默认逻辑是将所有嵌套路径展开为列名,在单行内输出所有叶子节点的值,和你需要的每行对应一条分支的结构逻辑不符,因此不适用该场景。
内容的提问来源于stack exchange,提问作者Ahmad
相关产品推荐
相关产品推荐

