Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge 2 lists containing obejcts with matching ids

Tags:

python

I have 2 lists that contain objects that look like this:

list 1:

{'name': 'Nick', 'id': '123456'}

list 2:

{'address': 'London', 'id': '123456'}

Now I want to create a third list, containing objects that look like this:

{'name': 'Nick', 'address': 'London', 'id': '123456'}

i.e, I want to find the matching id's, and merge those objects.

like image 808
Majs Avatar asked Oct 28 '25 03:10

Majs


1 Answers

you can use groupby to get all the matching dicts, then unify them using ChainMap, like this:

from itertools import groupby
from operator import itemgetter
from collections import ChainMap

list1 = [{'name': 'Nick', 'id': '123456'}, {'name': 'Donald', 'id': '999'}]
list2 = [{'address': 'London', 'id': '123456'}, {'address': 'NYC', 'id': '999'}]

grouped_subdicts = groupby(sorted(list1 + list2, key=itemgetter("id")), itemgetter("id"))

result = [dict(ChainMap(*g)) for k, g in grouped_subdicts]

print(result)

Output:

[{'id': '123456', 'address': 'London', 'name': 'Nick'},
{'id': '999', 'address': 'NYC', 'name': 'Donald'}]
like image 146
Adam.Er8 Avatar answered Oct 30 '25 14:10

Adam.Er8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!