[英]Python how to update a dictionary with another dictionary by applying add to existing values
我有一個包含字符串鍵和數值的現有字典。 我創建了另一個字典,其中包含我需要通過現有字典update
新鍵和值。
只有要求是我需要如果新詞典中的鍵已經存在於目標詞典中,則該值將被添加到現有值,而不是替換它。
我怎樣才能在Python 2.7中實現這一點?
看起來像從collections
使用Counter
的好例子:
>>> from collections import Counter
>>> d1 = Counter({'a':1,'b':1})
>>> d2 = Counter({'a':2,'c':3})
>>> d1.update(d2)
>>> d1
Counter({'a': 3, 'c': 3, 'b': 1})
您還可以創建新集合:
>>> d1 + d2
Counter({'a': 3, 'c': 3, 'b': 1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.