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>In order to achieve this, firstly create a dictionary to store your values. Then convert the <code>dict</code> object to <code>tuple list</code> using <code>.items()</code> Below is the sample code on how to achieve this:</p>

<pre><code>my_list = [ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
my_dict = {}
for key, val in my_list:
    if key in my_dict:
        my_dict[key] += val
    else:
        my_dict[key] = val

my_dict.items()
# Output: [('A', 150), ('C', 10), ('B', 70)]
</code></pre>

python list tuples