user2882093
user2882093

Reputation: 13

Combining first elements of nested lists and summing the second elements

I have a list like this:

list = [["r", 200], ["c,", 0.22], ["r", 5000]]

How can I combine the tuples with the same first item so that the result is like this:

list = [["r", 5200], ["c", 0.22]]

Is there some sophisticated way of doing this? The order of tuples doesn't matter.

Thanks

Upvotes: 1

Views: 50

Answers (2)

David Unric
David Unric

Reputation: 7719

With use of built-in functions:

lst = [["r", 200], ["c,", 0.22], ["r", 5000]]
res={}
for k,v in lst:
  res[k]=res.get(k, 0) + v
res
# {'r': 5200, 'c,': 0.22}

To get the result in the original type:

[[k, v] for k,v in res.iteritems()]
# [['r', 5200], ['c,', 0.22]]

Upvotes: 0

TerryA
TerryA

Reputation: 59974

You can use collections.defaultdict:

>>> from collections import defaultdict
>>> t = [["r", 200], ["c,", 0.22], ["r", 5000]]
>>> d = defaultdict(int)
>>> for i, j in t:
...     d[i] += j
... 
>>> print d.items()
[('r', 5200), ('c,', 0.22)]

By the way, don't name a list list. It will override the built-in type.

Upvotes: 1

Related Questions