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…