Search code examples
pythonlistzip

Python join two lists with first index in common


I have two python lists with the following data

list1 = [[datetime.date(2019, 12, 11), 4], [datetime.date(2019, 12, 14), 3]]
list2 = [[datetime.date(2019, 12, 14), 2], [datetime.date(2019, 12, 16), 9]]

I have to combine both list with first index ie., datetime.date field to be common. Also, if first index does not match for the both, set the value to.

Also if any of the list is blank, set the corresponding position to 0.

The resultant will be

list_new = [
   [datetime.date(2019, 12, 11), 4, 0],
   [datetime.date(2019, 12, 14), 3, 2],
   [datetime.date(2019, 12, 16), 0, 9]
]

I tried using zip like

new_list = [a + [b[1]] for (a, b) in zip(list1, list2)]

But this does not seems to be working.


Solution

  • Simple (non-optimal) one-liner:

    [[element, dict(list1).get(element, 0), dict(list2).get(element, 0)] for element in set([l[0] for l in list1 + list2])]
    

    Explanation:

    1. Get a set of unique first elements from the list:
    >>> s = set([l[0] for l in list1 + list2])
    >>> s
    set([datetime.date(2019, 12, 11), datetime.date(2019, 12, 14), datetime.date(2019, 12, 16)])
    
    1. Convert list of two elements to dict:
    >>> d1 = dict(list1)
    >>> d1
    {datetime.date(2019, 12, 11): 4, datetime.date(2019, 12, 14): 3}
    >>> d2 = dict(list2)
    >>> d2
    {datetime.date(2019, 12, 14): 2, datetime.date(2019, 12, 16): 9}
    
    
    1. Finally, form the resulting list:
    >>> [[element] + [d1.get(element, 0)] + [d2.get(element, 0)] for element in s]
    [[datetime.date(2019, 12, 11), 4, 0], [datetime.date(2019, 12, 14), 3, 2], [datetime.date(2019, 12, 16), 0, 9]]