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>

<pre><code>from collections import defaultdict

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

out = defaultdict(list)
[out[v[0]].append(v[1]) for v in lst]
out = [{"key": k, "value": sum(v)} for k, v in out.iteritems()]

print out
</code></pre>

python