YusufUMS
YusufUMS

Reputation: 1493

Combining 2 lists of lists in python

I am newbie in python. I need to merge 2 lists of lists based on the first element in each list. Here are the lists:

first_list = [['aaa', 551, 10972],
              ['bbb', 552, 10872],
              ['ccc', 553, 11103],
              ['ddd', 554, 10912]]

second_list = [['aaa', 240], 
               ['bbb', 120], 
               ['ccc', 325], 
               ['ddd', 270]]

The code I have written:

join_list = []
for x in range(0, len(first_list)):
    temp = [first_list[x], second_list[x][1]]
    join_list.append(temp)

The following is the output:

join_list =
[[['aaa', 551, 10972], 240],
 [['bbb', 552, 10872], 120],
 [['ccc', 553, 11103], 325],
 [['ddd', 554, 10912], 270]]

I need to flatten the list of the list in each element in join_list, e.g the first element in join_list[0] = ['histogram', 551, 10972, 240]. Also, if the order of the second list is change and if there is an addition of a sublist in the first element, the 2 lists is still can be merged based on the first index in each element. So, it works like the VLOOKUP or HLOOKUP in Ms.Excel. How can we do this?

Upvotes: 1

Views: 323

Answers (4)

DSLima90
DSLima90

Reputation: 2848

Maybe this is what you are looking for:

d = dict(second_list)
flat = [a+[d[a[0]]] for a in first_list]

It gives me:

flat = [['aaa', 551, 10972, 240],
 ['bbb', 552, 10872, 120],
 ['ccc', 553, 11103, 325],
 ['ddd', 554, 10912, 270]]

This way the order of your second list does not matter.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82805

Use chain from itertools to flatten

Demo:

first_list = [['aaa', 551, 10972],
              ['bbb', 552, 10872],
              ['ccc', 553, 11103],
              ['ddd', 554, 10912]]

second_list = [['aaa', 240], 
               ['bbb', 120], 
               ['ccc', 325], 
               ['ddd', 270]]

from itertools import chain
print([list(chain(*[v, [second_list[i][1]]])) for i, v in enumerate(first_list)])

Output:

[['aaa', 551, 10972, 240], ['bbb', 552, 10872, 120], ['ccc', 553, 11103, 325], ['ddd', 554, 10912, 270]]

Upvotes: 1

jpp
jpp

Reputation: 164843

This is one way which does not assume a specific ordering of either list.

d = dict(second_list)

res = [i + [d[i[0]]] for i in first_list]

[['aaa', 551, 10972, 240],
 ['bbb', 552, 10872, 120],
 ['ccc', 553, 11103, 325],
 ['ddd', 554, 10912, 270]]

Upvotes: 2

zipa
zipa

Reputation: 27899

You could introduce lookup dict and set default value in case there is no match:

lookup = dict(second_list)
default = 0
join_list = [i + [lookup.get(i[0], default)] for i in first_list]

Here, default is set to 0.

Upvotes: 2

Related Questions