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

如何使用glom将嵌套defaultdict扁平化为指定结构的记录列表

glom转换嵌套字典为记录列表实现方案

完整可运行代码

from collections import defaultdict
from glom import glom, Iter

# 构造示例嵌套字典
source = defaultdict(dict)
source["China"]["Beijing"] = {
    "num_persons" : 1454324,
    "num_cars" : 134
}
source["Greece"]["Athens"] = {
    "num_persons" : 2332,
    "num_cars" : 12
}

# 定义glom转换规则
spec = (
    # 遍历外层国家字典,得到(国家名, 城市数据字典)元组序列
    Iter.items()
    .map(
        lambda country, city_map: (
            # 遍历当前国家下的城市字典
            Iter(city_map.items())
            # 合并国家、城市字段与统计属性,生成单条记录
            .map(lambda city, stats: {"country": country, "city": city, **stats})
            .all()
        )
    )
    # 展开嵌套的列表结构为一维列表
    .flatten()
    .all()
)

# 执行转换得到结果
result = glom(source, spec)

输出结果验证

执行上述代码后result的值完全符合需求:

[
    {'country': 'China', 'city': 'Beijing', 'num_persons': 1454324, 'num_cars': 134},
    {'country': 'Greece', 'city': 'Athens', 'num_persons': 2332, 'num_cars': 12}
]

规则说明

  • Iter.items():将目标字典转换为键值对元组的迭代序列,适配多层嵌套遍历场景
  • map():对迭代序列的每个元素做转换,多层map分别处理国家层级和城市层级的信息
  • 字典解包语法**stats:直接将统计数据的键值对合并到结果记录中,无需手动逐个映射字段
  • flatten():将两层遍历生成的嵌套列表展开为一维的记录列表

内容的提问来源于stack exchange,提问作者Demeter P. Chen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:15:03