[英]How to merge two dictionaries in a list without overwriting the previous key
[英]Merge dictionaries without overwriting, rather an addition of value if key equality
有沒有辦法更新()一個字典而不是盲目地覆蓋同一個鍵的值? 例如,我想在我的策略中為相同的鍵添加值,如果我找到它,並連接如果找不到鍵。
d1 = {'eggs':3, 'ham':2, 'toast':1}
d2 = {'eggs':2,'ham':1}
dresult = d1.myUpdate(d2)
print dresult
{'eggs':5,'ham':3,'toast':1}
你可以使用一個計數器 (在python 2.7中引入):
from collections import Counter
d1 = {'eggs':3, 'ham':2, 'toast':1}
d2 = {'eggs':2,'ham':1}
dresult = Counter(d1) + Counter(d2) #Counter({'eggs': 5, 'ham': 3, 'toast': 1})
如果你需要一個適用於python2.5 +的版本,一個defaultdict
也可以工作(雖然不是很好):
from collections import defaultdict
d1 = {'eggs':3, 'ham':2, 'toast':1}
d2 = {'eggs':2,'ham':1}
d = defaultdict(int)
dresult.update(d1)
for k,v in d2.items():
dresult[k] += v
雖然你可以實現等效的python2。 結果使用字典的setdefault
方法...
使用櫃台:
from collections import Counter
d1 = Counter({'eggs':3, 'ham':2, 'toast':1})
d2 = Counter({'eggs':2,'ham':1})
print d1 + d2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.