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 top level of nested dict between Python 3.8 and 3.9

I have nested dict as following:

x1 = {'a1': 'val1', 
      'a2':'val2'}
x2 = {'b1': {'b1a':'val3'}, 
      'b2': {'b2a':'val3'}}

Both x1 and x2 can be multiple level nested dictionaries. But I just want to merge them at the top level, with this expected output:

x_merged = {'a1': 'val1', 
            'a2': 'val2', 
            'b1': {'b1a': 'val3'}, 
            'b2': {'b2a': 'val3'}}

In Python 3.9, I can do that easily with:

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

x_merged = x1 | x2

But in Python 3.8 and lower, that syntax is not accepted. I have to do:

x_merged = dict(x1.items() | x2.items())

But that statemment only works for one level dictionaries. I get TypeError: unhashable type: 'dict' for multi-level dictionaries.

Any short solution to this for Python 3.8 (beside writing a whole function such as this one)

>Solution :

The old {**x1, **x2} should work

Output:

{'a1': 'val1', 
 'a2': 'val2', 
 'b1': {'b1a': 'val3'}, 
 'b2': {'b2a': 'val3'}}
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