Write a Python Program to Merge Two Dictionaries with a practical example.
Python Program to Merge Two Dictionaries Example
In this program, we are using the update function to update first_Dict with second_Dict values.
first_Dict = {1: 'apple', 2: 'Banana' , 3: 'Orange'} second_Dict = { 4: 'Kiwi', 5: 'Mango'} print("First : ", first_Dict) print("Second : ", second_Dict) first_Dict.update(second_Dict) print("\nAfter Concatenating : ") print(first_Dict)
First : {1: 'apple', 2: 'Banana', 3: 'Orange'}
Second : {4: 'Kiwi', 5: 'Mango'}
After Concatenating :
{1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi', 5: 'Mango'}
Python Program to Concatenate Dictionaries Example 2
It is another way to merge 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.
first_Dict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange'} second_Dict = { 'k': 'Kiwi', 'm': 'Mango'} print("First : ", first_Dict) print("Second : ", second_Dict) print("\nAfter Concatenating : ") print(dict(first_Dict, **second_Dict) )
output
First : {'a': 'apple', 'b': 'Banana', 'o': 'Orange'}
Second : {'k': 'Kiwi', 'm': 'Mango'}
After Concatenating :
{'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'k': 'Kiwi', 'm': 'Mango'}
Concatenate Two Dictionaries Example
This code is the same as above. However, using Function, we separated the two dictionaries’ concatenation logic in this program.
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 third_Dict = Merge_Dictionaries(first_Dict, second_Dict) print("\nAfter Concatenating two Dictionaries : ") print(third_Dict)
