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

Python嵌套字典追加元素 解决update方法合并无效问题

为什么dict.update()达不到预期

Python原生字典的update()方法只做第一层键值的覆盖替换,不会递归处理嵌套结构。直接调用时,原字典里exist对应的整个子字典,会被新字典中exist对应的子字典整个覆盖,原来的name、country、team键会直接丢失,自然不符合需求。

正确实现方法

针对你当前的字典结构(嵌套层级均为字典,同路径下无重复键需要特殊处理),写一个简单的递归合并函数即可:

def deep_merge(origin: dict, target: dict) -> dict:
    for k, v in target.items():
        # 两边同键的值都是字典时,递归向下合并
        if k in origin and isinstance(origin[k], dict) and isinstance(v, dict):
            deep_merge(origin[k], v)
        # 其余情况直接新增/覆盖键值
        else:
            origin[k] = v
    return origin

# 测试代码
if __name__ == "__main__":
    origin = {"exist":{"name":["a","b"],"country":["US"],"team":["SP","FR"]}, "not_exist":{}}
    new_data = {"exist":{"age":[23,43,45],"sports":["football","rugby"]}, "not_exist":{"title":["Mr","Ms"]}}
    merged = deep_merge(origin, new_data)
    print(merged)

运行输出结果和预期完全一致:

{
    "exist": {
        "name": ["a", "b"],
        "country": ["US"],
        "team": ["SP", "FR"],
        "age": [23, 43, 45],
        "sports": ["football", "rugby"]
    },
    "not_exist": {"title": ["Mr", "Ms"]}
}

注意事项

  • 上述实现会直接修改传入的原始字典origin,如果需要保留原始数据不被改动,可以在合并前对原字典做一次深拷贝:
    import copy
    origin_copy = copy.deepcopy(origin)
    merged = deep_merge(origin_copy, new_data)
    
  • 如果后续业务中遇到同键对应的值都是列表、需要做列表元素追加/去重的场景,只需要在函数的判断分支里增加对应列表的处理逻辑即可,不需要改动整体递归框架。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 14:57:16