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

How to combine two nested dictionaries with same master keys

I have two nested dicts with same master keys:

dict1 = {'person1': {'name': 'John', 'sex': 'Male'},
         'person2': {'name': 'Marie', 'sex': 'Female'},
         'person3': {'name': 'Luna', 'sex': 'Female'},
         'person4': {'name': 'Peter', 'sex': 'Male'}}

dict2 = {'person1': {'weight': '81.1', 'age': '27'},
         'person2': {'weight': '56.7', 'age': '22'},
         'person3': {'weight': '63.4', 'age': '24'},
         'person4': {'weight': '79.1', 'age': '29'}}

So I want to enrich dict 1 by the key value pairs from dict2.

I’m able to do so with a for loop…

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

for key in dict2:
        dict2[key]['age'] = dict1[key]['age']
        dict2[key]['weight'] = dict2[key]['weight']

Result:

dict2 = {'person1': {'name': 'John', 'sex': 'Male', 'weight': '81.1', 'age': '27'},
         'person2': {'name': 'Marie', 'sex': 'Female', 'weight': '56.7', 'age': '22'},
         'person3': {'name': 'Luna', 'sex': 'Female', 'weight': '63.4', 'age': '24'},
         'person4': {'name': 'Peter', 'sex': 'Male', 'weight': '79.1', 'age': '29'}}

…but is there a more pythonic way to do so – e.g. with dict comprehension?

>Solution :

Yes:

dict3 = {k: {**v, **dict2[k]} for k, v in dict1.items()}

Firstly, use .items() to iterate over both keys and values at the same time.

Then, for each key k you want the value to be a new dict that is created by dumping — or destructuring — both v and dict2[k] in it.

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