Python Program to Merge Two Dictionaries

Write a Python Program to Merge Two Dictionaries with a practical example.

Python Program to Merge Two Dictionaries Example

In this python program, we are using the dictionary update function to update first_Dict with second_Dict values.

# Python Program to Concatenate Two Dictionaries

first_Dict = {1: 'apple', 2: 'Banana' , 3: 'Orange'}
second_Dict = { 4: 'Kiwi', 5: 'Mango'}
print("First Dictionary: ", first_Dict)
print("Second Dictionary: ", second_Dict)

# Concatenate Two Dictionaries in Python
first_Dict.update(second_Dict)
    
print("\nAfter Concatenating two Dictionaries : ")
print(first_Dict)

Python Merge two dictionaries output

First Dictionary:  {1: 'apple', 2: 'Banana', 3: 'Orange'}
Second Dictionary:  {4: 'Kiwi', 5: 'Mango'}

After Concatenating two Dictionaries : 
{1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi', 5: 'Mango'}

Python Program to Concatenate Dictionaries Example 2

It is another way to merge dictionaries in Python. In this program, we are using the dict keyword to create a new Dictionary using first_Dict and ** second_Dict. Here, ** allows you to pass multiple arguments.

# Python Program to Concatenate Two Dictionaries

first_Dict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange'}
second_Dict = { 'k': 'Kiwi', 'm': 'Mango'}
print("First Dictionary: ", first_Dict)
print("Second Dictionary: ", second_Dict)

# Concatenate Two Dictionaries in Python
print("\nAfter Concatenating two Dictionaries : ")
print(dict(first_Dict, **second_Dict) )

Python dictionary concatenation output

First Dictionary:  {'a': 'apple', 'b': 'Banana', 'o': 'Orange'}
Second Dictionary:  {'k': 'Kiwi', 'm': 'Mango'}

After Concatenating two Dictionaries : 
{'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'k': 'Kiwi', 'm': 'Mango'}

Python Program to Concatenate Two Dictionaries Example 3

This Python Dictionary concatenation code is the same as above. However, in this python program, we separated the two dictionaries concatenation logic using Python Function.

# Python Program to Concatenate Two Dictionaries

def Merge_Dictionaries(first, second):
    result = {**first_Dict, **second_Dict}
    return result

first_Dict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange'}
second_Dict = { 'k': 'Kiwi', 'm': 'Mango'}
print("First Dictionary: ", first_Dict)
print("Second Dictionary: ", second_Dict)

# Concatenate Two Dictionaries in Python
third_Dict = Merge_Dictionaries(first_Dict, second_Dict)

print("\nAfter Concatenating two Dictionaries : ")
print(third_Dict)
Python Program to Merge Two Dictionaries 3