apol96
apol96

Reputation: 210

Merging lists according to the first element

So I have three lists:

lst1 = [('test1', 0.2), ('test7', 0.2)]
lst2 = [('test1', 5.2), ('test2', 11.1), ('test7', 0.2)]
lst3 = [('test1', 19.2), ('test2', 12.1), ('test7', 19.2), ('test9', 15.1)]

What I want to do is to go through the lists and create the following tuple:

[(test1, 0.2, 5.2, 19.2), (test2, 0.0, 11.1, 12.1), (test7, 0.2, 0.2, 19.2), (test9, 0.0, 0.0, 15.1)]

The output has to be exactly as illustrated as it will be used further in my program. I have tried many approaches but it is really tricky to add that 0.0 there when there are no values in one of the lists.

Upvotes: 1

Views: 34

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do:

from collections import defaultdict


lst1 = [('test1', 0.2), ('test7', 0.2)]
lst2 = [('test1', 5.2), ('test2', 11.1), ('test7', 0.2)]
lst3 = [('test1', 19.2), ('test2', 12.1), ('test7', 19.2), ('test9', 15.1)]

table = defaultdict(lambda: defaultdict(float))
all_lst = [lst1, lst2, lst3]
for i, l in enumerate(all_lst):
    for e, v in l:
        table[e][i] = v

res = [tuple([key, *[values[i] for i in range(len(all_lst))]]) for key, values in sorted(table.items())]

print(res)

Output

[('test1', 0.2, 5.2, 19.2), ('test2', 0.0, 11.1, 12.1), ('test7', 0.2, 0.2, 19.2), ('test9', 0.0, 0.0, 15.1)]

The idea is to use a nested dictionary to keep track of the seen positions for each object. By default, when no value is present, a defaultdict of float will return 0.

Upvotes: 3

Related Questions