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.

| operator merges two dictionaries. If there are two same keys with different values on the two dictionaries, the later one is chosen for the merge operation.

In the above example, there are two key-value pairs with the same key 2. The later one 2:'c' is chosen for the merge.


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.

Using **, we can merge two dictionaries. ** considers the dictionary passed as arguments and merges them. To know more about **kwargs, please visit Python *args and **kwargs.


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'}

Here, we have first copied the content of dict_2 into dict_3 using copy() and then we update dict_3 with the values of dict_1 using update().

Did you find this article helpful?