Algorithm
-
Input: Two dictionaries,
dict1
anddict2
. -
Output: A new dictionary containing the merged key-value pairs from both dictionaries.
-
Algorithm:
- Create an empty dictionary, let's call it
merged_dict
. - Iterate through the key-value pairs in
dict1
.- Add each key-value pair to
merged_dict
.
- Add each key-value pair to
- Iterate through the key-value pairs in
dict2
.- Check if the key is already present in
merged_dict
.- If yes, update the value for that key.
- If no, add the key-value pair to
merged_dict
.
- Check if the key is already present in
merged_dict
now contains the merged key-value pairs from both dictionaries.
- Create an empty dictionary, let's call it
Code Examples
#1 Code Example- Using the | Operator
Code -
Python Programming
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print(dict_1 | dict_2)
Copy The Code &
Try With Live Editor
Output
{1: 'a', 2: 'c', 4: 'd'}
#2 Code Example- Using the ** Operator
Code -
Python Programming
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print({**dict_1, **dict_2})
Copy The Code &
Try With Live Editor
Output
{1: 'a', 2: 'c', 4: 'd'}
#3 Code Example- Using copy() and update()
Code -
Python Programming
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)
Copy The Code &
Try With Live Editor
Output
{2: 'b', 4: 'd', 1: 'a'}
Demonstration
Python Programing Example to Merge Two Dictionaries-DevsEnv