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

Python深度嵌套字典递归处理:空字典值键转为父节点值

Python嵌套字典结构转换实现方案

核心逻辑说明

你需要递归遍历嵌套字典,当检测到某个字典仅包含1个键,且该键对应的值是空字典{}时,用该键直接替换上层的字典结构即可。

完整实现代码

def transform(node):
    # 非字典类型直接返回
    if not isinstance(node, dict):
        return node
    # 先递归处理所有子节点
    processed_child = {}
    for k, v in node.items():
        processed_child[k] = transform(v)
    # 判断是否满足替换条件:仅1个键+对应值为空字典
    if len(processed_child) == 1:
        sole_key, sole_value = next(iter(processed_child.items()))
        if sole_value == {}:
            return sole_key
    # 不满足替换条件则返回处理后的子字典
    return processed_child

# 原始字典
d = {
    "config": {
        "application": {
            "payment": {
                "dev": {
                    "modes": {"credit,debit,emi": {}},
                    "company": {
                        "address": {
                            "city": {"London": {}},
                            "pincode": {"LD568162": {}},
                        },
                        "country": {"United Kingdom": {}},
                        "phone": {"7865432765": {}},
                    },
                    "levels": {"0,1,2": {}},
                },
                "prod": {"modes": {"credit,debit": {}}, "levels": {"0,1": {}}},
            }
        }
    }
}

# 执行转换
result = transform(d)
print(result)

输出验证

运行代码后得到的结果和目标结构完全一致:

{
    "config": {
        "application": {
            "payment": {
                "dev": {
                    "modes": "credit,debit,emi",
                    "company": {
                        "address": {
                            "city": "London",
                            "pincode": "LD568162"
                        },
                        "country": "United Kingdom",
                        "phone": "7865432765"
                    },
                    "levels": "0,1,2"
                },
                "prod": {
                    "modes": "credit,debit",
                    "levels": "0,1"
                }
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:18:02