mahmoud / glom

☄️ Python's nested data operator (and CLI), for all your declarative restructuring needs. Got data? Glom it! ☄️
https://glom.readthedocs.io
Other
1.89k stars 61 forks source link

Is there a way to merge two list based on their dict's key by glom? #205

Closed afeish closed 3 years ago

afeish commented 3 years ago

First, thanks for your awesome project.

Let's say we have two different list of dicts: list1 [{'id': 1, 'username': 'jack'}, {'id': 2, 'username': 'john'}] list2 [{'id': 1, 'username': 'tom'}, {'id': 3, 'username': 'kate'}]

I want to merge the two different list by id, and the later list take precedence. The final desired list will be: list3 [{'id': 1, 'username': 'tom'}, {'id': 2, 'username': 'john'},{'id': 3, 'username': 'kate'}]

Can I use glom to achieve this? I have already read the docs of the official or any solutions on stackoverflow. But still without any idea. Thanks in advance

mborus commented 3 years ago

Yes, by moving your list entries into a dictionary with the id as a key and then retrieving the values of that dict.

With your defined list1 and list2, you can use this code

from glom import glom, T, Iter, Merge
spec = Iter({T['id']: T}), Merge(), T.values(), list
print(glom(list1 + list2, spec))

This will result in

 [{'id': 1, 'username': 'tom'}, {'id': 2, 'username': 'john'}, {'id': 3, 'username': 'kate'}]

BTW, make sure to ask these kind of questions on stackoverflow and mark them with the glom tag for others to find them more easily.