Write A Python Script To Check If A Given Key Already Exists In The Dictionary

In this article let's learn about a dictionary containing a set of  key-value pairs,  declared within the Python program. Provided a key as an input to the Python program you have to check if the dictionary contains the key or not.

Let's use keyword in as an operator to find if a given key exists in a dictionary or not.

 

Python Script To Check If A Given Key Already Exists In The Dictionary

 

 
Write A Python Script To Check If A Given Key Already Exists In The Dictionary

Let's declare a dictionary named as fruits,  provide the key values as fruit names and value as cost of fruits.

fruits = {"apple": 56, "orange": 50, "grapes": 30, "lemon": 10}



Now take a string variable named as key and ask a user to enter the name of the key/ fruit name. Once the user enters a key, use the if statement to check if the key exists in the dictionary,  if so print the key exists, else the print key doesn't exist in the dictionary.

key = input("Enter a Fruit Name/ Key : ")
if key in fruits:
   print("Fruit Name / Key already Exists in Dictionary")
else:
   print("Fruit Name / Key doesn't Exists in Dictionary")




Python Script
==========================

fruits = {"apple": 56, "orange": 50, "grapes": 30, "lemon": 10}

key = input("Enter a Fruit Name/ Key : ")
if key in fruits:
   print("Fruit Name / Key already Exists in Dictionary")
else:
   print("Fruit Name / Key doesn't Exists in Dictionary")





Output
============
Enter a Fruit Name/ Key : strawberry
Fruit Name / Key doesn't Exists in Dictionary



Output
=============
Enter a Fruit Name/ Key : apple
Fruit Name / Key already Exists in Dictionary




Conclusion
==============
Modify the above Python program with students and their  marks scored in each subject,  accept He as student name and check if the student name exists in the dictionary or not, note down the results  after executing.

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





Post a Comment

0 Comments