- 12 Apr, 2012
- read
- Majid Fatemian
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': 'joe'} , {'id':3 , 'name':'jack'}]
y = [{'id':2 , 'num': 22} , {'id':3 , 'num': 33}]
And you want to get the final result like this :
[{'num': 22, 'id': 2, 'name': 'joe'}, {'num': 33, 'id': 3, 'name': 'jack'}]
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')