Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - update Dictionary By Incrementing

>>> 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

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

1 Reply

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...