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

Python如何将嵌套字典的多层key拼接为点分隔的扁平化key

实现方案

通过递归处理单个嵌套字典的扁平化逻辑,递归过程中维护当前的父级key前缀,遇到值为字典类型就继续递归拼接key,遇到非字典类型就把拼接好的key和对应值存入结果字典,该方案可以自动适配任意深度的嵌套层级,不会出现深层key漏处理的问题。

核心实现代码

def flatten_dict(nested_dict, parent_key='', sep='.'):
    items = []
    for k, v in nested_dict.items():
        # 拼接当前层级的key
        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())
        else:
            # 子元素非字典,直接存入结果
            items.append((new_key, v))
    return dict(items)

# 处理字典数组的入口函数
def flatten_dict_array(nested_array):
    return [flatten_dict(item) for item in nested_array]

测试示例

输入示例

test_array = [
    {
        "id": 1,
        "info": {
            "name": "test1",
            "contact": {
                "phone": "13xxxxxxxxx",
                "email": "test1@example.com"
            }
        },
        "code": 200
    },
    {
        "id": 2,
        "info": {
            "name": "test2",
            "contact": {
                "phone": "13yyyyyyyyy",
                "email": "test2@example.com"
            }
        },
        "code": {
            "status": 400,
            "msg": "error"
        }
    }
]

输出结果

[
    {
        "id": 1,
        "info.name": "test1",
        "info.contact.phone": "13xxxxxxxxx",
        "info.contact.email": "test1@example.com",
        "code": 200
    },
    {
        "id": 2,
        "info.name": "test2",
        "info.contact.phone": "13yyyyyyyyy",
        "info.contact.email": "test2@example.com",
        "code.status": 400,
        "code.msg": "error"
    }
]

如果你的数据中还包含列表类型需要扁平化,只需要在flatten_dict函数中补充isinstance(v, list)的分支逻辑,按照需求拼接索引到key中即可。

内容的提问来源于stack exchange,提问作者Le Roy Loïc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:18:03