valenzio valenzio - 1 month ago 5
Python Question

Merge two lists together

I have two lists in python:

L1=[[100, 1], [101, 2]]
L2=[[100, 3], [101, 4], [102, 5]]


and I want to merge them so I get:

L_merge=[[100, 4], [101, 6], [102, 5]]


It is important that the two lists might be not of the same size.

I was trying to use dictionaries but could not figure it out. I am happy to use numpy, pandas or any other tools to get that merger.

Answer

You could use a collections.Counter on both lists and simply sum them:

from collections import Counter

L1 = [[100, 1], [101, 2]]
L2 = [[100, 3], [101, 4], [102, 5]]

L_merge = (Counter(dict(L1)) + Counter(dict(L2))).items()
print(list(L_merge))
# [(100, 4), (101, 6), (102, 5)]