Majs
Majs

Reputation: 56

Merge 2 lists containing obejcts with matching ids

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.

Upvotes: 4

Views: 685

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13403

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'}]

Upvotes: 7

Related Questions