How to outer join list of lists in Python?

Viewed 796

I have two lists of lists in Python that I would like joined together. The structure and desired result is as follows:

ListofLists1 = [['20200701', DF_x1], ['20200702', DF_x2], ...]
ListofLists2 = [['20200702', DF_y2], ['20200704', DF_y4], ...]
ListofLists3 = [['20200702', DF_z2], ['20200707', DF_z7], ...]
ListofLists4 = [['20200702', DF_a2], ['20200704', DF_a4], ...]

DesiredList = [['20200701', DF_x1, ''   , ''   , ''   ], 
               ['20200702', DF_x2, DF_y2, DF_z2, DF_a2], 
               ['20200704', ''   , DF_y4, DF_z4, ''   ], 
               ['20200707', ''   , ''   , ''   , DF_a7]] 

As you can see, each element of the original lists contains a date and a dataframe. I would like these lists merged, such that one date corresponds with all available dataframes for that date. Each sublist contains 3 elements. This would need to be an outer join, as each list-of-lists contains elements which the other does not.

1 Answers

First create a dictionary with the values from the first list, then update it with the values from the second one:

d = {l[0]: [l[1], ''] for l in ListofLists1}

for l in ListofLists2:
    d.setdefault(l[0], ['', ''])[1] = l[1]

Converting the dictionary back to a list, if needed:

joined_list = [[k, *v] for k, v in d.items()]
Related