Python Program to Check if a Key Exists in a Dictionary or Not

This is a Python Program to check if a given key exists in a dictionary or not.

Problem Description

The program takes a dictionary and checks if a given key exists in a dictionary or not.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the dictionary using the dictionary.keys() method.
4. If it is present, print the value of the key.
5. If it isn’t present, display that the key isn’t present in the dictionary.
6. Exit.

Program/Source Code

Here is source code of the Python Program to check if a given key exists in a dictionary or not. The program output is also shown below.

d={'A':1,'B':2,'C':3}
key=raw_input("Enter key to check:")
if key in d.keys():
      print("Key is present and value of the key is:")
      print(d[key])
else:
      print("Key isn't present!")
Program Explanation

1. User must enter the key to be checked and store it in a variable.
2. An if statement and the in operator is used check if the key is present in the list containing the keys of the dictionary.
3. If it is present, the value of the key is printed.
4. If it isn’t present, “Key isn’t present!” is printed.
5. Exit.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter key to check:A
Key is present and value of the key is:
1
 
Case 2:
Enter key to check:F
Key isn't present!

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.