Hi, In this article lets learn how to demo the working of dictionary in Python Programming Language.
Dictionary Definition : Dictionary is the set of key value pairs, separated by comma enclosed in two flower braces, having key as unique. Where every value is associated with a key. Key is used as index in dictionary to access value.
Valid data types of keys are string, numbers and tuples. Value can be any data type example, string, numbers, lists, tuple, set, dictionary.
Example :
Create Empty dictionary
basket = dict()
Create Dictionary Containing Subjects and Marks Scored by Student
subjects = {"Science": 50, "Mathematics" : 70, "English" : 57}
Below is the Program to Demonstrate Working With Dictionaries in Python
This program is divided in to four section, Create, Read, Update and Delete (CRUD) secitions of dictionary. Where we first try to create dictionary, Read the dictionary, Update and finally Delete the Dictionary.
Phase 1 : Create a Dictionary of fruits with their costs.
fruits = {"apple" : 150, "banana" : 50, "orange" : 40}
Phase 2 : Read the dictionary by printing fruits in store with their costs
print("\nBelow is the cost of fruits : ")
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
Phase 3 : Update the fruits with Strawberry cost 100 and print Dictionary
print("\nAdding Strawberry to Store Items")
fruits["strawberry"] = 100
print("\nBelow is the cost of fruits : ")
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
Phase 4a : Assuming Apple got over in Store Delete the Apple key and display menu items
del fruits["apple"]
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
Phase 4b : Delete all the fruits from store, using clear dictionary.
fruits.clear()
Final Program :
fruits = {"apple" : 150, "banana" : 50, "orange" : 40}
print("\nBelow is the cost of fruits : ")
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
print("\nAdding Strawberry to Store Items")
fruits["strawberry"] = 100
print("\nBelow is the cost of fruits : ")
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
print("\nDeleting apple from store")
del fruits["apple"]
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
del fruits["apple"]
for key, value in fruits.items():
print(f"Fruits : {key} Costs : {value}")
fruits.clear()
Conclusion : Hope you enjoyed reading this article, please comment if you have any queries. Also subscribe to YouTube channel and the blog.
Keywords : Write a Program to Demonstrate Working With Dictionaries in Python
0 Comments