Articles

Program to check if a particular key is present in the dictionary in Python

Program to check if a particular key is present in the dictionary in Python


In the basic python programming article, we are going to learn

  • program to find whether a particular key is present in the dictionary in python

Program to check if a particular key is present in the dictionary in Python

The program is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

db = {
    1 : "Devjeet Roy",
    2 : "Ajit Agarwal",
    3 : "Dhananda Seth",
    4 : "Dhanush Singh"
}

search_key = int(input("Enter the key to be search for: "))

if search_key in db.keys():
    print("The key has been found!")
else:
    print("The key is not found!")

The output of the program is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter the key to be search for: 2
The key has been found!
PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter the key to be search for: 99
The key is not found!

Few important tips about the program

1. If the name of the dictionary is "db", the "db.keys()" returns us the name of all the keys of that dictionary in an iterable format. We can convert that to a list or tuple.

2. The "in" operator is used to check if a particular key is present in the dictionary.

 

if a particular key is present in the python dictionary

 


Basic Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :    Published Date : Oct 13,2022  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!