How to merge two dicts in Python?

Method 1: Update

Note: This method changes the first dictionary

>>> a = {1: 1}
>>> b = {2: 2}
>>> a.update(b)
>>> print(a)
{1: 1, 2: 2}

Method 2: Using ** (>= Python 3.5)

>>> a = {1: 1}
>>> b = {2: 2}
>>> c = {**dict1, **dict2}
>>> print(c)  
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Method 3: Using the | Operator (>= Python 3.9)

>>> a = {1: 1}
>>> b = {2: 2}
>>> c = {**dict1, **dict2}
>>> print(c)  
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
12/2024