0

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)

Tristan Tran
  • 1,351
  • 1
  • 10
  • 36

2 Answers2

1

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

Output:

{'a1': 'val1', 
 'a2': 'val2', 
 'b1': {'b1a': 'val3'}, 
 'b2': {'b2a': 'val3'}}
mcsoini
  • 6,280
  • 2
  • 15
  • 38
1

For Python@3.5 and greater (PEP 448):

x_merged = {**x1, **x2}
Dmitry Barsukoff
  • 152
  • 1
  • 13