1

I have a list of tuples as:

values = [('n', 2), ('b', 5), ('d',6), ('b',3)]

I would like to add the integer value if the first element is the same so I get a new list as:

valuesNew = [('n', 2), ('b', 8), ('d',6)]

I would appreciate any help. Thanks!

  • Thanks for accepting my answer. I recommend you take a look at some of the answers on the linked page, as they are a lot more clever than mine :) – Tom Fenech May 22 '14 at 17:18

1 Answers1

1

Here's one way you could do it. You lose the ordering of the original tuple, as dictionaries aren't ordered.

d = dict()
for key, val in values:
    if key in d:
        d[key] += val
    else:
        d[key] = val

valuesNew = [(k,v) for k,v in d.iteritems()]

gives you:

>>> valuesNew
[('b', 8), ('d', 6), ('n', 2)]
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141