Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

>>> D1 = {'potatoes':2.67,'sugar':1.98,'cereal':5.99,'crisps':1.09} 
>>> D2 = {'parsley':0.76,'cereal':3.22} 
>>> D1 = updateDictionaryByIncrementing(D1, D2) 

How can I update the keys/values of D1 based on the content of D2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...