如何将含嵌套字典的列表转换为扁平化结构的CSV文件?
解决嵌套字典列表转CSV的格式问题
问题说明
将嵌套字典列表转换为CSV文件时,输出不符合预期:
当前CSV输出
type name color ownerinfo cat fred blue [{'name': 'Mary','phonenumber':'123'}] cat ben orange [{'name':'Dan', 'phonenumber':'234'}]
期望CSV输出
type name color name phonenumber cat fred blue Mary 123 cat ben orange Dan 234
原Python代码
import json import pandas as pd #Open and load files as list with open("data.json", "rb") as f: data = json.load(f)["objects"] # Get cat cats = [a for a in data if "cat" in a.get("type")] df = pd.DataFrame(cats) #store cat in csv df.to_csv('in.csv')
解决方案
问题核心是ownerinfo字段是包含单字典的列表,直接转DataFrame会保留列表结构。需要将嵌套字典展开并合并到原数据中,再生成CSV:
修改后的代码
import json import pandas as pd # 加载数据 with open("data.json", "r") as f: data = json.load(f)["objects"] # 筛选cat类型数据 cats = [a for a in data if "cat" in a.get("type")] # 展开嵌套字典并合并数据 processed_cats = [] for cat in cats: # 取出ownerinfo列表中的字典(假设每个cat对应一个owner) owner_data = cat.pop("ownerinfo")[0] # 合并原cat数据与owner数据 processed_cats.append({**cat, **owner_data}) # 生成CSV df = pd.DataFrame(processed_cats) df.to_csv('out.csv', index=False, sep='\t')
代码说明
- 用
cat.pop("ownerinfo")[0]取出嵌套字典,同时移除原数据中的ownerinfo字段 - 通过
{**cat, **owner_data}将原数据与嵌套字典合并,把嵌套字段转为平级列 index=False避免生成索引列,sep='\t'指定制表符分隔,匹配示例格式
内容的提问来源于stack exchange,提问作者user18774110
相关产品推荐
相关产品推荐

