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>You can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(int)</code></a> from <code>collections</code> module:</p>

<pre><code>&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt; d = defaultdict(int)
&gt;&gt;&gt; for key, value in lists:
...     d[key] += value[0]
... 
&gt;&gt;&gt; dict(d)
{'Gifts': 8, 'Prints': 3, 'Accounts': 6, 'Features': 5, 'Supply': 8, 'Politics': 9}
&gt;&gt;&gt; list(d.items())
[('Prints', 3), ('Features', 5), ('Supply', 8), ('Gifts', 8), ('Accounts', 6), ('Politics', 9)]
</code></pre>

python list python-3.x