How to sum list of tuples?
<p>I have a list of tuples:</p>

<pre><code>[ (a,1), (a,2), (b,1), (b,3) ]
</code></pre>

<p>I want to get the sum of both the <code>a</code> and <code>b</code> values. The results should be in this format:</p>

<pre><code>[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ]
</code></pre>

<p>How can I do this?</p>

<p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> to create a <a href="https://en.wikipedia.org/wiki/Multiset" rel="nofollow"><em>multiset</em></a> from the initial list and then modify the result to match your case:</p>

<pre><code>from collections import Counter

lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]

part = sum((Counter({i[0]: i[1]}) for i in lst), Counter())
# Counter({'b': 4, 'a': 3})

final = [{'key': k, 'value': v} for k, v in part.items()]
# [{'key': 'b', 'value': 4}, {'key': 'a', 'value': 3}]
</code></pre>

python