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>How about this: (assuming <code>a</code> is the name of the tuple you have provided)</p>

<pre><code>letters_to_numbers = {}
for i in a:
    if i[0] in letters_to_numbers:
        letters_to_numbers[i[0]] += i[1]
    else:
        letters_to_numbers[i[0]] = i[1]
b = letters_to_numbers.items()
</code></pre>

<p>The elements of the resulting tuple <code>b</code> will be in no particular order.</p>

python list tuples