简体   繁体   English

替代python中的dict.update

[英]alternative to dict.update in python

So I realized that 所以我意识到了

dict1.update(dict2)

replaces values of dict2 with dict1 if the key exists in both the dictionaries. 如果两个字典中都存在键,则用dict1替换dict2的值。 Is there any way to add the values of dict2 to dict1 directly if the key is present instead of looping around the key,value pairs 有没有办法直接将dict2的值添加到dict1,如果键存在而不是循环键,值对

You say you want to add the values, but not what type they are. 您说您想要添加值,但不是它们的类型。 If they are numeric, you may be able to use collections.Counter instead of dict 如果它们是数字,您可以使用collections.Counter而不是dict

>>> from collections import Counter
>>> a = Counter({'a':1, 'b':2})
>>> b = Counter({'a':5.4, 'c':6})
>>> a + b
Counter({'a': 6.4, 'c': 6, 'b': 2})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM