0

I have a nested list that looks like this:

nested = [['a', 1], ['v', 2], ['a', 5], ['v', 3]]

I want to sum values in nested list for each letter value in list, so that output looks like this:

[['a', 6], ['v', 5]]

I have tried to play with for loops, but I couldnt find the solution.

taga
  • 3,537
  • 13
  • 53
  • 119

1 Answers1

0

There is probably a one liner for this using reduce and list comp, but I couldn't see it quickly.

nested = [['a', 1], ['v', 2], ['a', 5], ['v', 3]]

from collections import defaultdict
d = defaultdict(int)
for i in nested:
    d[i[0]] += i[1]

retval = []    
for k, v in d.items():
    retval.append([k, v])

print(retval)  # [['a', 6], ['v', 5]]
JacobIRR
  • 8,545
  • 8
  • 39
  • 68