<p>可以使用<a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">^{<cd1>}</a>,首先将<code>.items()</code>作为字典,然后根据键的第一个元素对列表进行排序,并将<a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">^{<cd1>}</a>作为键的第一个元素(元组<code>key,value</code>的第一个元素)。然后,对于每个组,您可以对值进行<code>sum()</code>运算以获得所需的值。示例-</p>
<pre><code>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)
</code></pre>
<p>请注意,您的结果有点错误,您的字典也有点错误,因为<code>dictionary</code>不能有多个值的同一个键。你知道吗</p>
<p>演示-</p>
<pre><code>>>> 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
</code></pre>