简体   繁体   English

合并字典而不覆盖,而是在密钥相等时添加值

[英]Merge dictionaries without overwriting, rather an addition of value if key equality

Is there a way to update() a dictionnary without blindly overwriting values of the same key ? 有没有办法更新()一个字典而不是盲目地覆盖同一个键的值? For example i want in my strategy to add value for the same key if i find it, and concatenate if key is not found. 例如,我想在我的策略中为相同的键添加值,如果我找到它,并连接如果找不到键。

d1 = {'eggs':3, 'ham':2, 'toast':1}
d2 = {'eggs':2,'ham':1}

dresult = d1.myUpdate(d2)

print dresult 
{'eggs':5,'ham':3,'toast':1}

You can use a Counter for this (introduced in python 2.7): 你可以使用一个计数器 (在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})

If you need a version which works for python2.5+, a defaultdict could also work (although not as nicely): 如果你需要一个适用于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

Although you could achieve an equivalent python2.? 虽然你可以实现等效的python2。 result using a dictionary's setdefault method... 结果使用字典的setdefault方法...

Use a Counter: 使用柜台:

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.

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