Python : Merge three lists of tuples according the first element of the tuple to add the seconds elements

Python : Merge three lists of tuples according the first element of the tuple to add the seconds elements

Problem Description:

I have three lists of tuples of size 2 given by :

a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]

I want to merge them and remove the duplicates according the first element of the tuples. With the second, we add them. So we should get

a = [(47, 300) , (0, 86), (4, 86), (39, 90)]

How can i do that ?

Thank you

Solution – 1

combined = a1 + a2 + a3
seen = set()
desired_output = [(a, b) for a, b in combined if not (a in seen or seen.add(a))]

EDIT:
I missed the part of the question of summing up the numbers. Sorry about that. Here is my edited answer addressing that part:

mydict = dict()

for a, b in combined:
   if a in mydict:
      mydict[a] += b
   else:
      mydict[a] = b

final_tuple = list(mydict.items())

Solution – 2

Try:

a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]

out = {}
for l in [a1, a2, a3]:
    for x, y in l:
        out[x] = out.get(x, 0) + y

out = list(out.items())
print(out)

Prints:

[(47, 300), (0, 86), (4, 86), (39, 90)]
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject