Sum of dictionaries

2

I'm working with python and django and I have several data dictionaries that I want to add up for a total. All dictionaries can have two keys primera and segunda , but I must get a total of both primera and segunda and a general total of both

totalinterno = {u'segunda': Decimal('1.3880'), u'primera': Decimal('18.1671')}

totalimportado = {u'segunda': Decimal('0.5000')}

totalmaquila = {u'primera': Decimal('0.3000')}

I would like to obtain the following results:

{'segunda': Decimal('1.8880'), 'primera': Decimal('18.4671')}

Maybe it's something simple but I'm new to this and I do not know how to do it, if someone would be so kind to explain or guide me a little I would be very grateful

    
asked by Moriko 05.01.2018 в 01:06
source

2 answers

0

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')}
    
answered by 05.01.2018 / 02:02
source
0

Well dictionaries can not be added in mathematical terms (+), so what you can do is add the keys to get the total, that is, totalinterno['primera'] + totalmaquila['primera'] , only if you are sure that the value is numeric data , in this case I see that you have a function called "Decimal", if you want to pass it to decimal then you can choose to use the default function of Python called float(cadena_numero) .

    
answered by 05.01.2018 в 01:35