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

使用for循环对多字典同键值求和时遇覆盖问题

解决字典相同键值累加的问题

你的问题出在使用a.update(i)的时候——这个方法的作用是直接用新字典的键值对覆盖目标字典里的同名键,所以遍历到最后一个字典时,之前的累加值都被覆盖了,自然得不到求和的结果。

下面给你几种可行的实现方式:

方法一:基础for循环遍历(适合新手理解)

手动遍历每个字典的键值对,判断键是否已经在结果字典里,存在就累加,不存在就直接赋值:

x = {'both1':0, 'both2':2, 'only_x': 100 }
y = {'both1':1, 'both2': -200, 'only_y':203 }
z = {'both1':5, 'both2': 400, 'only_y':13 }

a = {}
for d in [x, y, z]:
    for key, value in d.items():
        if key in a:
            a[key] += value
        else:
            a[key] = value
print(a)

运行结果就是你想要的:

{'both1': 6, 'both2': 202, 'only_x': 100, 'only_y': 216}

方法二:使用collections.defaultdict(更简洁)

利用defaultdict可以给不存在的键设置默认值的特性,省去判断键是否存在的步骤:

from collections import defaultdict

x = {'both1':0, 'both2':2, 'only_x': 100 }
y = {'both1':1, 'both2': -200, 'only_y':203 }
z = {'both1':5, 'both2': 400, 'only_y':13 }

a = defaultdict(int)
for d in [x, y, z]:
    for key, value in d.items():
        a[key] += value
# 如果需要转换成普通字典,可以用dict(a)
print(dict(a))

方法三:使用collections.Counter(适合纯数值场景)

Counter本身就是用来计数的容器,支持直接相加操作,非常适合这种场景:

from collections import Counter

x = {'both1':0, 'both2':2, 'only_x': 100 }
y = {'both1':1, 'both2': -200, 'only_y':203 }
z = {'both1':5, 'both2': 400, 'only_y':13 }

# 把每个字典转成Counter后相加
a = Counter(x) + Counter(y) + Counter(z)
print(dict(a))

注:Counter的相加会正常保留值为0的键,测试结果和期望完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:59:02