Python Program to Merge Two Dictionaries – 2024

Hey guys, in this blog we will see a Python Program to Merge Two Dictionaries.

Example 1: Using the | Operator

# Python Program to Merge Two Dictionaries

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

print(dict_1 | dict_2)

Output

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

We have used “|” operator to find the Union of the two dictionaries.

Example 2: Using the ** Operator

# Python Program to Merge Two Dictionaries

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

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

Output

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

Here we have used “**” to merge two dictionaries here. “**dict1” will print all the content of dict1 and similarly for dict2.

Example 3: Using copy() and update()

# Python Program to Merge Two Dictionaries

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

Simply using dict.update() method to update a dictionary with another dictionary.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *