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.

0

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.