Sum values of tuples stored as key value pair in list by key
<p>I have a list like <code>[('a',2),('a',3),('b',3),('c',2),('b',4)]</code></p>

<p>I want to sum all similar keys and get <code>[('a',5),('c',2),('b',7)]</code> in any order is fine.</p>

<p>Is there a better way to do this instead of using a dictionary. Preferably using list comprehension something like <code>[i for j in a for ...]</code></p>

<pre><code>&gt;&gt;&gt; a = [('a',2),('a',3),('b',3),('c',2),('b',4)]
&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt; d = defaultdict(int)
&gt;&gt;&gt; for i,j in a:
...   d[i] += j 
... 
&gt;&gt;&gt; d
defaultdict(&lt;type 'int'&gt;, {'a': 5, 'c': 2, 'b': 7})
&gt;&gt;&gt; zip(d.keys(),d.values())
[('a', 5), ('c', 2), ('b', 7)]
</code></pre>

<p>In Python-3, the last line requires <code>list(zip(d.keys(),d.values()))</code></p>