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.
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With