How to sum values ​​from python dictionary with key as tuple

I have the following dictionary with the key as tuple

D_grpTagReport = { ('Tag1', '1'):345.56 ,
                   ('Tag1', '2'):45.6 ,
                   ('Tag2', '3'):3.1 ,
                   ('Tag3', '1'):21.56 ,
                   ('Tag2', '3'):1.56 ,
                 }

I would like to get the sum of the values ​​for each unique tag. Is there a built-in utility that can be used to process this dictionary.

Example result:

Tag1 : 391.16     # (total of all Tag1)
Tag2 : 4.66       # (total of all Tag2) 
Tag3 : 21.56      # (total of all Tag3) 
+4
source share
3 answers

itertools.groupby , .items() , itertools.groupby key ( key,value). sum() , , . -

from itertools import groupby
for key,group in groupby(sorted(D_grpTagReport.items()),key=lambda x:x[0][0]):
    total = sum(g[1] for g in group)
    print(key,':',total)

, , , dictionary .

-

>>> D_grpTagReport = { ('Tag1', '1'):345.56 ,
...                    ('Tag1', '2'):45.6 ,
...                    ('Tag2', '3'):3.1 ,
...                    ('Tag3', '1'):21.56 ,
...                    ('Tag2', '3'):1.56 ,
...                  }
>>>
>>>
>>> from itertools import groupby
>>> for key,group in groupby(sorted(D_grpTagReport.items()),key=lambda x:x[0][0]):
...     total = sum(g[1] for g in group)
...     print(key,':',total)
...
Tag1 : 391.16
Tag2 : 1.56
Tag3 : 21.56
+1

defaultdict:

>>> from collections import defaultdict
>>> D_grpTagReport = { ('Tag1', '1'):345.56 ,
...                    ('Tag1', '2'):45.6 ,
...                    ('Tag2', '3'):3.1 ,
...                    ('Tag3', '1'):21.56 ,
...                    ('Tag2', '3'):1.56 ,
...                  }
>>> result = defaultdict(int)
>>> for t in D_grpTagReport:
...     result[t[0]] += D_grpTagReport[t]
...
>>> result
defaultdict(<class 'int'>, {'Tag3': 21.56, 'Tag1': 391.16, 'Tag2': 1.56})
+2

Some good answers already exist, but here is a different (simpler IMO) approach.

d = {('A', '1'): 2, ('A', '2'): 5, ('B', '1'): 1}
keys={k[0]:0 for k in d.keys()}
for key in d:
    keys[key[0]] = keys[key[0]] + d[key]
print(keys)  # {'A': 7, 'B': 1}

Once again with the data from the OP:

d = { ('Tag1', '1'):345.56 ,
      ('Tag1', '2'):45.6 ,
      ('Tag2', '3'):3.1 ,
      ('Tag3', '1'):21.56 ,
      ('Tag2', '3'):1.56 ,
    }
keys={k[0]:0 for k in d.keys()}
for key in d:
    keys[key[0]] = keys[key[0]] + d[key]
print(keys)  # {'Tag1': 391.16, 'Tag2': 1.56, 'Tag3': 21.56}
+2
source

Source: https://habr.com/ru/post/1612535/


All Articles