Home > Net >  Merging top level of nested dict between Python 3.8 and 3.9
Merging top level of nested dict between Python 3.8 and 3.9

Time:04-08

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:

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)

CodePudding user response:

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

Output:

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

CodePudding user response:

For [email protected] and greater (PEP 448):

x_merged = {**x1, **x2}
  • Related