Skip to content
Advertisement

Adding values list of tuples on the basis of key

I have two lists of tuples, consider tuple’s 1st element as key and second one as value.

Input: [[(1, 100), (2, 100), (3, 100)], [(1, 100), (4, 100), (5, 100)]]
Output: [(1, 200), (2, 100), (3, 100), (4, 100), (5, 100)] 

I am a bit new to python, unable to start off with this problem.

Advertisement

Answer

Use collections.defaultdict

Ex:

from collections import defaultdict

res = defaultdict(int)
data = [[(1, 100), (2, 100), (3, 100)], [(1, 100), (4, 100), (5, 100)]]
for i in data:
    for k, v in i:
        res[k] += v
print(list(res.items()))

Output:

[(1, 200), (2, 100), (3, 100), (4, 100), (5, 100)]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement