Skip to content
Advertisement

How to combine two nested dictionaries with same master keys

I have two nested dicts with same master keys:

JavaScript

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

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

JavaScript

Result:

JavaScript

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

Advertisement

Answer

Yes:

JavaScript

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.

UPDATE for Python >= 3.9:

Thanks @mwo for mentioning the pipe | operand:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement