【发布时间】:2015-09-22 10:49:01
【问题描述】:
给定三个字典 d1、d2 和 d3:
d1
{'a':1,'b':2,'c':3, 'd':0)
d2
{'b':76}
d3
{'a': 45, 'c':0}
有一些键名对多个 dict 是通用的(实际上,它们将代表同一个现实生活中的对象)。其他如 d1 中的 'd' 仅存在于 d2 中。我想将所有 dicts 组合在一起,首先将公共键的值相加,最终得到:
{'a':46, 'b':78, 'c':3, 'd': 0}
如果每个字典的大小相同并且包含相同的键,我可以这样做:
summedAndCombined = {}
for k,v in d1.items():
summedAndCombined[k] = d1[k]+d2[k]+d3[k]
但是,一旦它到达 d1 中但不在其他中的键,它就会崩溃。我们如何实现这一目标?
更新
不是重复的。 collections.Counter 几乎可以工作,但是如果键 d 的值为零,则结果 Counter 中缺少键 d。 p>
In [128]: d1 = {'a':1,'b':2,'c':3, 'd':0}
In [129]: d2 = {'b':76}
In [130]: d3 = {'a': 45, 'c':0}
In [131]: from collections import Counter
In [132]: Counter(d1) + Counter(d2) + Counter(d3)
Out[132]: Counter({'b': 78, 'a': 46, 'c': 3})
【问题讨论】:
-
if k in d2.keys() ...
标签: python python-2.7 dictionary iteration defaultdict