简体   繁体   English

如何将具有键作为元组的python字典中的值相加

[英]how to sum values from a python dictionary having key as tuple

I have the following dictionary with 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 values for each unique Tag. 我想得到每个唯一标签的值的总和。 Is there any built in utility that can be used to process this dictionary. 是否有可用于处理此字典的内置实用程序。

Result Example: 结果示例:

Tag1 : 391.16     # (total of all Tag1)
Tag2 : 4.66       # (total of all Tag2) 
Tag3 : 21.56      # (total of all Tag3) 

You could use a defaultdict : 你可以使用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})

Some good answers already, but here's a different (simpler IMO) approach. 已有一些好的答案,但这里有一个不同的(更简单的IMO)方法。

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 more with the data from the OP: 再次使用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}

You can use itertools.groupby for this , first take .items() for the dictionary and then sort this list based on the first element of the key and the use itertools.groupby on it with key as the first element of the key (first element of first element of the tuple of key,value ). 你可以使用itertools.groupby ,首先取字典的.items() ,然后根据键的第一个元素对该列表进行排序,并使用itertools.groupbykey作为key的第一个元素(第一个) key,value元组的第一个元素元素。 Then for each group you can take sum() over the values to get what you want. 然后,对于每个组,您可以对值取sum()以获得所需的值。 Example - 示例 -

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)

Please note you result is a bit wrong, and so is your dictionary, since dictionary cannot have same key with multiple values. 请注意,结果有点不对,你的字典也是如此,因为dictionary不能有多个值的相同键。

Demo - 演示 -

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM