Sum list values where index 0 values match?
<p>I have a list of lists and I want to merge them to sum the inner <code>index[1]</code> values where the <code>index[0]</code> values match. My list looks like this:</p>

<pre><code>lists = [
['Gifts', [4]],
['Gifts', [4]],
['Politics', [3]],
['Supply', [4]],
['Supply', [4]],
['Prints', [1]],
['Prints', [1]],
['Prints', [1]],
['Politics', [3]],
['Politics', [3]],
['Accounts', [2]],
['Accounts', [2]],
['Accounts', [2]],
['Features', [3]],
['Features', [2]]
]
</code></pre>

<p>I would therefore like the new structure to be:</p>

<pre><code>new_lists = [
['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]
</code></pre>

<p>How do I achieve this in Python?</p>

<p>Use a <code>defaultdict</code>:</p>

<pre><code>In [52]: from collections import defaultdict

In [53]: d = defaultdict(int)

In [54]: for name, (val,) in lists:
   ....:     d[name] += val
   ....:     

In [55]: d.items()
Out[55]: dict_items([('Politics', 9), ('Supply', 8), ('Prints', 3), ('Features', 5), ('Gifts', 8), ('Accounts', 6)])
</code></pre>

python list python-3.x