You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含嵌套字典的列表转换为扁平化结构的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:45:42