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>Or, use a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> from <a href="https://docs.python.org/3/library/collections.html" rel="nofollow"><code>collections</code></a>. You can initialize it either manually by incrementing the values for every key:</p>

<pre><code>from collections import Counter

c = Counter()
for i, j in lists:
    c[i] += l[j]
</code></pre>

<p>Or, by providing a flat list of the expanded contents, <code>Counter</code> will then do the counting for you:</p>

<pre><code>c = Counter(sum([[i] * j[0] for i,j in lists], []))
</code></pre>

<p>In both cases, create the result list by using a list comprehension grabbing the contents of the counter with <code>c.items()</code>:</p>

<pre><code>r = [[i, j] for i, j in c.items()]
</code></pre>

<p>Result being:</p>

<pre><code>print(r) 
[['Supply', 8], ['Features', 5], ['Prints', 3],
 ['Gifts', 8], ['Accounts', 6], ['Politics', 9]]
</code></pre>

python list python-3.x