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

如何在Python 3中优雅实现含列表的字典扁平化?

Python 3中优雅实现含列表的字典扁平化

需求说明

需要将嵌套字典扁平化,同时把列表的索引作为键纳入扁平化路径,后续用于flatten -> merge -> unflatten流程实现列表对应位置字典的合并(现有工具仅支持列表追加/替换)。

输入示例

{
  "a": 1,
  "b": {
    "c": 2
  },
  "d": [3,4],
  "e": [
    {
      "f": 5
    },
    {
      "g": 6
    }
  ]
}

输出示例

{
  "a": 1,
  "b.c": 2,
  "d.0": 3,
  "d.1": 4,
  "e.0.f": 5,
  "e.1.g": 6
}

方案一:使用成熟库实现

优先推荐flatten-dict库,它原生支持将列表索引转为路径部分的场景:

  1. 安装库:
pip install flatten-dict
  1. 代码示例:
from flatten_dict import flatten

input_data = {
  "a": 1,
  "b": {
    "c": 2
  },
  "d": [3,4],
  "e": [{"f":5}, {"g":6}]
}

# 用dot作为路径分隔符,自动处理列表索引
flattened = flatten(input_data, reducer='dot')
print(flattened)

执行结果:

{'a': 1, 'b.c': 2, 'd.0': 3, 'd.1': 4, 'e.0.f': 5, 'e.1.g': 6}

方案二:自定义递归实现

如果不想依赖第三方库,可以编写递归函数处理:

def flatten_dict(data, parent_key='', sep='.'):
    items = []
    for k, v in data.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep).items())
        elif isinstance(v, list):
            for idx, item in enumerate(v):
                list_key = f"{new_key}{sep}{idx}"
                if isinstance(item, (dict, list)):
                    items.extend(flatten_dict(item, list_key, sep).items())
                else:
                    items.append((list_key, item))
        else:
            items.append((new_key, v))
    return dict(items)

# 测试
input_data = {
  "a": 1,
  "b": {
    "c": 2
  },
  "d": [3,4],
  "e": [{"f":5}, {"g":6}]
}

print(flatten_dict(input_data))

这段代码会递归遍历嵌套结构:

  • 遇到字典时继续拼接键路径并递归
  • 遇到列表时将索引作为路径片段,再处理列表内的嵌套元素
  • 最终返回符合要求的扁平化字典

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:26:25