3

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 Answer 1

3

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()]
Sign up to request clarification or add additional context in comments.

5 Comments

This worked precisely, thank you! I thought it might have something to do with dictionaries, but I don't know enough about them yet to have executed it myself. I will still need to chew on this solution a bit to understand how it all works, but I am thankful!
Nice answer. Very close to the solution I had rolling around in my head; just hadn’t written the answer yet. +1 mate.
Good, but I would use a collections.defaultdict(list) instead of a plain dict. It's simpler and more concise.
To generalize this solution a bit, I now have 4 lists of lists, rather than 2. How would I combine all 4? See the edit above. Thanks again!
@DylanMoore the empty list then needs to be ['', '', '', ''] and the for loop needs to be done for list 2 to 4. Be careful updating the correct position; not always [1].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.