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

Python实现含嵌套字典的多层列表遍历并写入带表头CSV

解决Python中嵌套列表字典导出带表头CSV的问题

嘿,我刚好能帮你搞定这个问题!要把这种带嵌套字典的多层列表数据导出到带表头的CSV,还得保留层级结构,核心就是先把嵌套的字段「展平」成CSV能识别的扁平表头,下面是具体的实现步骤和代码:

核心思路

CSV是扁平结构,没法直接存储嵌套数据,所以我们需要把嵌套的键(比如properties.xyz、geometry.coordinates[0])转换成CSV的表头字段,同时提取对应层级的值,这样就能在CSV里保留原数据的层级关系。

实现代码

我们可以写一个递归函数来展平嵌套字典和列表,再用Python内置的csv模块写入文件:

import csv

def flatten_dict(d, parent_key='', sep='.'):
    """递归展平嵌套字典和列表,保留层级关系"""
    items = []
    for k, v in d.items():
        # 拼接父键和子键,用sep分隔(默认是点号)
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            # 如果是字典,递归展平
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        elif isinstance(v, list):
            # 如果是列表,给每个元素加上索引标记(比如coordinates[0])
            for i, item in enumerate(v):
                list_key = f"{new_key}[{i}]"
                items.append((list_key, item))
        else:
            # 普通值直接加入
            items.append((new_key, v))
    return dict(items)

# 你的示例数据
data = {
    "features": [ 
        { 
            "type": "Feature", 
            "properties": { "xyz": 1, "abc": "pqr", "mmi": None }, 
            "geometry": { "type": "pt", "coordinates": [ -118.8957, 38.8607, 5.3 ] }, 
            "id": "abc101" 
        }
    ]
}

# 1. 展平每个feature对象
flattened_features = [flatten_dict(feature) for feature in data['features']]

# 2. 收集所有表头(确保不重复,保留首次出现的顺序)
headers = []
for feature in flattened_features:
    for key in feature.keys():
        if key not in headers:
            headers.append(key)

# 3. 写入CSV文件
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    # 用DictWriter来自动匹配表头和值
    writer = csv.DictWriter(csvfile, fieldnames=headers)
    writer.writeheader()  # 写入表头
    writer.writerows(flattened_features)  # 写入所有行

效果说明

运行代码后生成的output.csv表头会是:
type, properties.xyz, properties.abc, properties.mmi, geometry.type, geometry.coordinates[0], geometry.coordinates[1], geometry.coordinates[2], id

对应的数据行则会准确填充每个层级的值,比如properties.mmi对应的空值会在CSV里显示为空单元格,完全符合你的需求。

如果你的features列表里有多个元素,这个代码也能自动处理所有条目,不需要额外修改。

内容的提问来源于stack exchange,提问作者Medha Trivedi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:39:15