[英]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.