Write A Python Script To Concatenate Following Dictionaries To Create A New One


Given more than one dictionary as input to the Python program,  you have to write a logic where you have to concatenate two dictionaries and form a new dictionary.

Python provides update function call to concatenate two dictionaries into one so let's use update function call to to concatenate more than one dictionary dictionary.

 

 

Write A Python Script To Concatenate Following Dictionaries To Create A New One

 


Write A Python Script To Concatenate Following Dictionaries To Create A New One

In the  below program let's take two dictionaries declared inside the program, the two dictionaries named sweet_fruits and the other dictionary named it citrus_fruits.  provide some random key and value pair as contents of the dictionary.



sweet_fruits = {"apple": 150, "banana" : 30, "orange": 90}
citrus_fruits = {"orange": 120, "lemon": 20}





Now take an Empty dictionary named as fruits,   using the for loop to iterate all the items/ fruits present in two dictionaries by making a list of them,  when we iterate all the items present in the dictionary use the update function call to to update the dictionary.

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





Once the for loop is completed using the print function called print the new dictionary  as shown below.

print(fruits)





Complete python program
=========================


sweet_fruits = {"apple": 150, "banana" : 30, "orange": 90}
citrus_fruits = {"orange": 120, "lemon": 20}

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

print(fruits)





Output
===============
{'apple': 150, 'banana': 30, 'orange': 120, 'lemon': 20}




Conclusion
================
Execute the above Python program by providing different set of dictionaries as a input to the Python program modify the dictionary values and note down the results after execution

Comment down below if you have any suggestions to improve the above Python program.
 


Post a Comment

0 Comments