Merging Python List of Dictionaries based on specific key

This post is completely based on a cool post on StackOverflow.

So this is the situation, you have two list which they have dictionaries in and you want to merge the dictionaries if they have the same value for one specific field.


x = [{'id':2 , 'name': 'majid'} , {'id':3 , 'name':'maral'}]
y = [{'id':2 , 'num': 22} , {'id':3 , 'num': 33}]

And you want to get the final result like this :

[{'num': 22, 'id': 2, 'name': 'majid'}, {'num': 33, 'id': 3, 'name': 'maral'}]

The function which does the job is as follow (Written by Adam in StackOverflow) :

def merge_lists(l1, l2, key):
  merged = {}
  for item in l1+l2:
    if item[key] in merged:
      merged[item[key]].update(item)
    else:
      merged[item[key]] = item
  return [val for (_, val) in merged.items()]

Now you can test it easily :

merge_lists(x, y , 'id')