As Andres answered, the elements of the dictionaries can be added arithmetically with the +
method:
from decimal import *
totalinterno = {u'segunda': Decimal('1.3880'), u'primera': Decimal('18.1671')}
totalimportado = {u'segunda': Decimal('0.5000')}
totalmaquila = {u'primera': Decimal('0.3000')}
print(totalinterno['segunda']+totalimportado['segunda'])
> 1.8880
Now, if you want to add the complete set of dictionaries and get a new dictionary with the updated elements, you can use the class Counter()
import collections
counter = collections.Counter()
for d in [totalinterno, totalimportado, totalmaquila]:
counter.update(d)
print(dict(counter))
{'segunda': Decimal('1.8880'), 'primera': Decimal('18.4671')}
What does take into account the operation of the +
method with string elements, in this case they are concatenated:
counter.clear()
d1={'algo': 'a'}
d2={'algo': 'b'}
for d in [d1, d2]:
counter.update(d)
print(dict(counter))
> {'algo': 'ba'}
I was thinking about something that Andrés commented about that dictionaries can not be added in mathematical terms , which is true, but nothing prevents us from creating our own dictionary class that implements the sum ( +
). For example:
from collections import Counter
class SumarizeDict(dict):
def __init__(self,*arg,**kw):
super(SumarizeDict, self).__init__(*arg, **kw)
self._counter = Counter(self)
def __add__(self, other):
if isinstance(other, dict):
self._counter.update(other)
return SumarizeDict(self._counter)
else:
return NotImplemented
md = SumarizeDict()
print(md)
md = md + totalinterno + totalimportado + totalmaquila
print(md)
> {}
> {'segunda': Decimal('1.8880'), 'primera': Decimal('18.4671')}