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):
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With