2017-04-02 36 views
1

我想用Python中的另一個字典更新一個字典,但是如果有一些相同的參數,應該添加它們的值。 例如:Python - 添加一個字典到另一個

a = {"word_1" : 1, "word_2": 2} 
b = {"word_2" : 5, "word_3": 7} 

輸出必須:

{"word_1" : 1, "word_2": 7, "word_3": 7} 

我用Google搜索了很多,但在大多數的答案值重寫,我想將它們添加 這裏是我的解決方案:

for i in a.keys(): 
     if i in b.keys(): 
      b[i] += a[i] 
     else: 
      b[i] = a[i] 

有沒有最有效的方法來做到這一點?

回答

8

使用Counter,這是一種用於計數對象的特殊字典。

from collections import Counter 

a = Counter({"word_1" : 1, "word_2": 2}) 
b = Counter({"word_2" : 5, "word_3": 7}) 
print(a + b) 

打印

Counter({'word_2': 7, 'word_3': 7, 'word_1': 1}) 
4

如何:

{k: a.get(k, 0) + b.get(k, 0) for k in set(list(a.keys()) + list(b.keys()))} 
+0

類型錯誤:不支持的操作數類型(S)爲+: 'dict_keys' 和 'dict_keys' –

+0

@OleksandrPryhoda,遺憾沒在Python3上測試,請再試一次,我已更新我的回答 – shizhz

+0

它的工作原理,它很好的變體,但與計數器,它的工作更快 –

相關問題