Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merging two list of dictionaries based on key

dict1 = [{'id': 1.0, 'name': 'aa'},
 {'id': 4.0, 'name': 'bb'},
 {'id': 2.0, 'name': 'cc'}]

and

dict2 = [{'name': 'aa', 'dtype': 'StringType'},
 {'name': 'bb', 'dtype': 'StringType'},
 {'name': 'xx', 'dtype': 'StringType'},
 {'name': 'cc', 'dtype': 'StringType'}]

I would like to merge this two dictionaries based on their common key which is name.

I would like to get the following desired result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

merged_dict= [{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},
 {'id': 4.0, 'name': 'bb', 'dtype': 'StringType'},
 {'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}]

I was trying to get this using the following for loop.

for i in dict1:
    for j in dict2:
         j.update(i)

>Solution :

To avoid quadratic complexity, better first create a real dictionary (yours are lists of dictionaries), then update:

tmp = {d['name']: d for d in dict2}

for d in dict1:
    d.update(tmp.get(d['name'], {}))

print(dict1)

Output:

[{'id': 1.0, 'name': 'aa', 'dtype': 'StringType'},
 {'id': 4.0, 'name': 'bb', 'dtype': 'StringType'},
 {'id': 2.0, 'name': 'cc', 'dtype': 'StringType'}]

Intermediate tmp:

{'aa': {'name': 'aa', 'dtype': 'StringType'},
 'bb': {'name': 'bb', 'dtype': 'StringType'},
 'xx': {'name': 'xx', 'dtype': 'StringType'},
 'cc': {'name': 'cc', 'dtype': 'StringType'}}

If you want a copy (rather that modifying dict1 in place):

tmp = {d['name']: d for d in dict2}
merged_dict = [d|tmp.get(d['name'], {}) for d in dict1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading