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')
Advertisements

5 thoughts on “Merging Python List of Dictionaries based on specific key

  1. I don’t even know how I ended up here, but I thought this post
    was good. I do not know who you are but definitely you’re going to a famous blogger if you are not
    already 😉 Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s