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

如何合并包含嵌套子字典的两个Python字典并更新公共键的值

嵌套字典合并实现方案

基础实现(适合初学者,无第三方依赖)

实现逻辑很简单,分三步:

  • 先复制第一个字典的全部内容到结果字典
  • 遍历第二个字典的每一个顶层键:
    • 顶层键不存在于结果字典时,直接写入对应的子字典
    • 顶层键已存在时,遍历对应子字典的键值对,公共键值相加,新键直接写入

示例代码如下:

d1 = {'Cat': {'White': 1}, 'Dog': {'Brown': 4, 'White': 2}}
d2 = {'Cat': {'Grey': 6, 'White': 3}, 'Rabbit': {'Brown': 4, 'White': 2}}

# 初始化结果字典,复制d1的顶层结构
combined = d1.copy()

for top_key, sub_dict in d2.items():
    if top_key in combined:
        # 已存在的顶层键,合并子字典
        for sub_key, count in sub_dict.items():
            # 子键存在就累加值,不存在就取0加当前值
            combined[top_key][sub_key] = combined[top_key].get(sub_key, 0) + count
    else:
        # 不存在的顶层键直接写入
        combined[top_key] = sub_dict

print(combined)

运行后输出结果和预期一致:
{'Cat': {'White': 4, 'Grey': 6}, 'Dog': {'Brown': 4, 'White': 2}, 'Rabbit': {'Brown': 4, 'White': 2}}

通用封装版本

如果后续需要合并更多同结构的嵌套字典,可以把逻辑封装成函数,支持传入任意多个字典参数:

def merge_nested_count_dict(*dicts):
    merged_result = {}
    for current_dict in dicts:
        for top_key, sub_dict in current_dict.items():
            if top_key not in merged_result:
                merged_result[top_key] = sub_dict.copy()
                continue
            for sub_key, count in sub_dict.items():
                merged_result[top_key][sub_key] = merged_result[top_key].get(sub_key, 0) + count
    return merged_result

# 调用示例
combined = merge_nested_count_dict(d1, d2)

注意事项

  • 以上实现仅适用于当前场景:仅两层嵌套、子字典值均为可累加的数值类型
  • 实现过程中做了数据隔离,修改合并后的字典不会影响原始的d1、d2数据

内容的提问来源于stack exchange,提问作者markovv.sim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:04