Sum numbers by letter in list of tuples
<p>I have a list of tuples: </p>

<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>

<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>

<pre><code>[('A', 150), ('B', 70), ('C',10)] 
</code></pre>

<p>I have tried using set to get the unique values but then when I try and compare the first elements to the set I get </p>

<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>

<p>Any quick solutions to match the numbers by letter?</p>

<p>What is generating the list of tuples? Is it you? If so, why not try a defaultdict(list) to append the values to the right letter at the time of making the list of tuples. Then you can simply sum them. See example below. </p>

<pre><code>&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt; val_store = defaultdict(list)
&gt;&gt;&gt; # next lines are me simulating the creation of the tuple
&gt;&gt;&gt; val_store['A'].append(10)
&gt;&gt;&gt; val_store['B'].append(20)
&gt;&gt;&gt; val_store['C'].append(30)
&gt;&gt;&gt; val_store
defaultdict(&lt;class 'list'&gt;, {'C': [30], 'A': [10], 'B': [20]})
&gt;&gt;&gt; val_store['A'].append(10)
&gt;&gt;&gt; val_store['C'].append(30)
&gt;&gt;&gt; val_store['B'].append(20)
&gt;&gt;&gt; val_store
defaultdict(&lt;class 'list'&gt;, {'C': [30, 30], 'A': [10, 10], 'B': [20, 20]})

&gt;&gt;&gt; for val in val_store:
...   print(val, sum(val_store[val]))
... 
C 60
A 20
B 40
</code></pre>

python list tuples