python

Merge two or multiple dictionaries in Python

There are several ways to merge or concatenate two or more dictionaries in python. In this post, We will explain the methods and techniques to join two or more dictionaries in Python.

Using the merge() method (Python 3.9+):

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = dict1 | dict2
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Using the update() method:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)
print(dict1)    # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Using the ** operator:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

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

Using the chain() method from the itertools module:

from itertools import chain

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = dict(chain(dict1.items(), dict2.items()))
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Was this helpful?