如何展平含重复键的深层嵌套字典并生成Pandas DataFrame?
自动展平嵌套字典生成完整Pandas DataFrame
假设你的嵌套字典示例结构如下(含重复键深层嵌套):
data = [ { "id": 1, "name": "ItemA", "attributes": [ {"attr_key": "size", "attr_val": "L"}, {"attr_key": "color", "attr_val": "red"} ] }, { "id": 2, "name": "ItemB", "attributes": [ {"attr_key": "size", "attr_val": "M"}, {"attr_key": "color", "attr_val": "blue"} ] } ]
要不用硬编码record_path或meta实现完整展平,可通过递归识别嵌套列表路径,再结合pd.json_normalize处理:
import pandas as pd def get_record_paths(obj, parent_path=""): """递归查找所有含字典元素的列表字段路径""" paths = [] for key, val in obj.items(): current_path = f"{parent_path}.{key}" if parent_path else key if isinstance(val, list) and val and isinstance(val[0], dict): paths.append(current_path) # 递归遍历子字典找更深层的列表 paths.extend(get_record_paths(val[0], current_path)) elif isinstance(val, dict): paths.extend(get_record_paths(val, current_path)) return paths # 从第一条数据中自动识别所有可能的列表路径 sample = data[0] all_paths = get_record_paths(sample) # 取最底层的列表路径,确保子记录全展开 target_path = all_paths[-1] if all_paths else None # 自动生成meta字段:顶层非列表字段 meta_fields = [k for k in sample.keys() if not isinstance(sample[k], list)] # 第一次展开列表 df = pd.json_normalize(data, record_path=target_path, meta=meta_fields) # 二次展平剩余的嵌套字典(如果有) df = pd.json_normalize(df.to_dict("records")) print(df)
核心逻辑
get_record_paths自动遍历字典结构,定位所有需要展开的嵌套列表,不用手动写路径。- 选择最底层列表路径展开,保证每条子记录都被单独成行,避免数据丢失。
- 二次调用
pd.json_normalize确保所有嵌套字典都被展平成列。
运行后会得到包含所有4条记录的DataFrame,完全覆盖原始数据的所有信息。
内容的提问来源于stack exchange,提问作者QuestionMan
相关产品推荐
相关产品推荐

