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

高效求和两个字典中共同键对应的值

字典键值求和实现

我有两个字典:

arr1 = {749: 3}
arr2 = {652: -1, 790: -1, 749: 5}

想要得到字典arr3,要求两个字典中共同键对应的值求和,非共同键保留原值,最终结果如下(无需排序):

arr3 = {652: -1, 790: -1, 749: 8}

由于时间性能至关重要,我目前使用的实现代码如下:

summated = {k : sum(i for i in (arr1.get(k), arr2.get(k)) if i is not None) for k in arr1.keys() | arr2}

另外,移除结果中值为0的键的代码如下:

{k:v for k,v in summated.items() if v}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:42:00