Python Program to Merge Two Dictionaries

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


Example 1: Using the | 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'}

In Python 3.9 and later versions, the | operator can be used to merge dictionaries.

Note: If there are two keys with the same name, the merged dictionary contains the value of the latter key.


Example 2: Using the ** 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'}

In the above program, we have used ** to unpack dictionaries dict_1 and dict_2. Then, the dictionaries are merged by placing them inside {}.

To know more about **kwargs, visit Python *args and **kwargs.

Note: The above code 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'}

Here, we have first copied the elements of dict_2 to dict_3 using the dictionary copy() method. Then, we updated dict_3 with the values of dict_1 using the dictionary update() method.


Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to merge two dictionaries.

  • Return the merged dictionary.
  • For example, for inputs {'a': 1, 'b': 2} and {'c': 3, 'd': 4}, the output should be {'a': 1, 'b': 2, 'c': 3, 'd': 4}.
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community