通过递增更新字典 [英] update Dictionary By Incrementing

查看:224
本文介绍了通过递增更新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 >>> D1 = {'土豆':2.67,'糖':1.98,'谷物':5.99,'crisps':1.09} 
>>> D2 = {'parsley':0.76,'cereal':3.22}
>>> D1 = updateDictionaryByIncrementing(D1,D2)

如何更新D1的键/值, D2的内容

解决方案

您可以使用循环键:



< D2中的密钥pre>
D1 [key] = D1.get(key,0)+ D2 [key]
/ pre>

或者您可以使用 collections.Counter()对象:

 从集合导入计数器

D1 = dict(计数器(D1)+计数器(D2))

演示后一种技术:

  >>>从集合导入计数器
>>>> D1 = {'土豆':2.67,'糖':1.98,'谷物':5.99,'crisps':1.09}
>>> D2 = {'parsley':0.76,'cereal':3.22}
>>>计数器(D1)+计数器(D2)
计数器({'谷物':9.21,'土豆':2.67,'糖':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}


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

解决方案

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}

这篇关于通过递增更新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆