Join our newsletter for the latest updates.

Python Program to Merge Two Dictionaries

In this example, you will learn to merge two dictionaries into one in Python programming.

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using operator |

dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}

print(dict_1|dict_2)

Output

{1: 'a', 2: 'c', 4: 'd'}

Note: It works for python 3.9 and above versions only.


Example 2: Using operator **

dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}

print({**dict_1, **dict_2})

Output

{1: 'a', 2: 'c', 4: 'd'}

Note: It works for python 3.5 and above versions.


Example 3: Using copy() and update()

dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}

dict_3 = dict_2.copy()
dict_3.update(dict_1)

print(dict_3)

Output

{2: 'b', 4: 'd', 1: 'a'}