You can use looping over the keys:
for key in D2:
D1[key] = D1.get(key, 0) + D2[key]
or you can use collections.Counter()
objects:
from collections import Counter
D1 = dict(Counter(D1) + Counter(D2))
Demo of the latter technique:
>>> from collections import Counter
>>> D1 = {'potatoes':2.67,'sugar':1.98,'cereal':5.99,'crisps':1.09}
>>> D2 = {'parsley':0.76,'cereal':3.22}
>>> Counter(D1) + Counter(D2)
Counter({'cereal': 9.21, 'potatoes': 2.67, 'sugar': 1.98, 'crisps': 1.09, 'parsley': 0.76})
>>> dict(Counter(D1) + Counter(D2))
{'cereal': 9.21, 'parsley': 0.76, 'sugar': 1.98, 'potatoes': 2.67, 'crisps': 1.09}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…