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

基于预定义映射递归转换Python嵌套字典的技术咨询

嵌套结构字典的递归转换实现

嘿,针对你提到的需要遍历包含字符串、字典、列表嵌套的字典,基于业务预定义映射生成新字典的场景,我这里有个适配「一对一键转换、删除指定键值对」需求的初始实现,代码框架如下:

def recursively_transform(parent_keys='', current_key='', container=None):
    container_class = container.__class__
    new_container_value = None
    if container is not None:
        # 处理字典类型
        if isinstance(container, dict):
            new_container = container_class()
            for key, value in container.items():
                # 从预定义映射里取目标键,没映射就保留原键
                mapped_key = predefined_mapping.get(key, key)
                # 如果映射值为None,就跳过这个键(相当于删除)
                if mapped_key is not None:
                    # 递归处理嵌套值,传递父键路径方便后续扩展复杂映射
                    new_container[mapped_key] = recursively_transform(
                        f"{parent_keys}.{key}" if parent_keys else key,
                        mapped_key,
                        value
                    )
            new_container_value = new_container
        # 处理列表类型
        elif isinstance(container, list):
            new_container = container_class()
            for idx, item in enumerate(container):
                # 列表元素按索引标记路径,递归处理每个元素
                new_container.append(
                    recursively_transform(
                        f"{parent_keys}[{idx}]",
                        str(idx),
                        item
                    )
                )
            new_container_value = new_container
        # 处理字符串等非容器类型的值,直接返回
        else:
            new_container_value = container
    return new_container_value

核心逻辑说明

  • 递归遍历全层级:不管是字典的嵌套子项还是列表里的元素,都会逐层递归处理,不会遗漏嵌套结构
  • 映射驱动的键处理:
    • 一对一转换:通过predefined_mapping字典配置原键到新键的映射,自动替换键名
    • 键删除:如果某个键在映射里对应的值是None,就会跳过该键值对,实现删除效果
  • 保留原始结构:处理后的结果会和原数据保持一致的容器类型(字典/列表),不会破坏原有数据结构

简单使用示例

假设业务给的预定义映射是这样的:

predefined_mapping = {
    "user_name": "username",  # 一对一重命名
    "phone": None,  # 删除phone这个键
    "address.street": "address.street_name"  # 支持嵌套键的映射,需要结合parent_keys判断扩展
}

调用代码转换原始字典:

original_data = {
    "user_name": "John Doe",
    "phone": "123456789",
    "address": {"street": "Main St", "zip": "10001"}
}
transformed_data = recursively_transform(container=original_data)

这个初始方案在需求仅为一对一转换和删除键时足够轻量,如果后续需要更复杂的逻辑(比如修改值的格式、多键合并等),直接在对应类型的处理分支里扩展就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:21:05