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>Very similar to answers given already. Little bit longer, but easier to read, IMHO.</p>

<pre><code>from collections import defaultdict

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

dd = defaultdict(int)
for name, value in lst:
    dd[name] += value

final = [{'key': k, 'value': v} for k, v in dd.items()]
</code></pre>

<p>(last line copied from Moses Koledoye's answer)</p>

python