Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 680
reyman64 Avatar asked Dec 20 '25 11:12

reyman64


1 Answers

You can use a Counter for this (introduced in 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):

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.? result using a dictionary's setdefault method...

like image 87
mgilson Avatar answered Dec 23 '25 01:12

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!