Write A Python Script To Merge Two Dictionaries

In this article let's learn how to write a python script to merge a dictionary. You can also use this script to merge more than two dictionaries.


Let's use the builtin update() function to merge two dictionaries into one, and then look into the other two types of merging by iterating the second dictionary.

 

Write A Python Script To Merge Two Dictionaries

 

Write A Python Script To Merge Two Dictionaries

Let's take an example of two dictionaries that are sweet fruits and citrus fruits,  declare both the dictionaries inside the program and assign some values. These are some of the random ki value presses that I have taken in order to get to the dictionary.


sweet_fruits = {"apple": 120, "banana": 30, "watermelon": 50, "mango": 50}
citrus_fruits = {"lemon": 50, "orange": 90, "mango": 90}



Now take an Empty  dictionary And use the for loop to iterate all the items present in the dictionary and update into a new dictionary as shown below.

fruits = {}
for item in [sweet_fruits, citrus_fruits]:
   fruits.update(item)



Once the for loop is completed you will be having the two-dictionary merged into a single dictionary named as fruits now using the for loop to iterate all the key values and print the key value pair.

for key, value in fruits.items():
   print(f"{key} : {value}")





Python Code
=====================

sweet_fruits = {"apple": 120, "banana": 30, "watermelon": 50, "mango": 50}
citrus_fruits = {"lemon": 50, "orange": 90, "mango": 90}

fruits = {}
for item in [sweet_fruits, citrus_fruits]:
   fruits.update(item)

for key, value in fruits.items():
   print(f"{key} : {value}")







Above python script is to show how to merge more than two dictionaries,  if you have only  two exact dictionaries then  use the below script to merge two dictionaries into one.

sweet_fruits = {"apple": 120, "banana": 30, "watermelon": 50, "mango": 50}
citrus_fruits = {"lemon": 50, "orange": 90, "mango": 90}

for item in [citrus_fruits]:
  sweet_fruits.update(item)
 
for key, value in sweet_fruits.items():
  print(f"{key} : {value}")





You can also do this by iterating second dictionary key value pair and then merging the key value pair to the first dictionary

sweet_fruits = {"apple": 120, "banana": 30, "watermelon": 50, "mango": 50}
citrus_fruits = {"lemon": 50, "orange": 90, "mango": 90}

for key, value in citrus_fruits.items():
  sweet_fruits[key] = value

for key, value in sweet_fruits.items():
  print(f"{key} : {value}")




Output
===============
apple : 120
banana : 30
watermelon : 50
mango : 90
lemon : 50
orange : 90




Conclusion
=====================
Take two dictionaries declared inside the main program, use the for loop to iterate all the items present in the list of dictionaries and add it to the new dictionary.


Comment it down below if you have any suggestion to improve the above python program.






Post a Comment

0 Comments