Algorithm


  1. Input: Two dictionaries, dict1 and dict2.

  2. Output: A new dictionary containing the merged key-value pairs from both dictionaries.

  3. 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.
    • 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.
    • merged_dict now contains the merged key-value pairs from both dictionaries.

 

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

x
+
cmd
{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

x
+
cmd
{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

x
+
cmd
{2: 'b', 4: 'd', 1: 'a'}
Advertisements

Demonstration


Python Programing Example to Merge Two Dictionaries-DevsEnv