0

I have two tuples

A=[(1,Poland),(2,Canada),(3,Germany)]
B=[(1,16),(2,20),(3,54)]

How can i merge them together based on the first value of a tuple to get something like this

C=[(Poland,16),(Canada,20),(Germany,54)]

I found This but this answer is from 2015 maybe you know better solution. My data will be at most 10/20 tuples so we aren't dealing with huge datasets

3 Answers3

1

If the tuples are always ordered as in the example, this is an easy case and you can simply use zip:

C = []
for a,b in zip(A, B):
    C.append(a[1], b[1])

#  or simply C = [(a[1], b[1]) for a,b in zip(A, B)]

If the order is not guaranteed (which makes the first number actually necessary), I would first convert one list to a dict, and then simply match the couples:

b_dict = dict(B)
C = []
for i, country in A:
    C.append((country, b_dict[i]))

#  or C = [(country, b_dict[i]) for i, country in A]

Of course this might require some handling of edge cases but I will leave that to you.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

This could be a solution.

[(x[1], y[1]) for y in B for x in A if x[0] == y[0]]
mustafasencer
  • 723
  • 4
  • 12
0

This look like a problem for pandas. You can turn them into pandas.Series() objects or pandas.DataFrame() and have the first number of the tuple as the index. Then just use the pandas.DataFrame.merge() to merge by index and you will have the three column dataframe or series.

Alternatively it would have to be a nested loop:

C = []
for i in A:
    for j in B:
        if i[0] == j[0]:
            C.append((i[1], j[1]))