This is a Python Program to check if a given key exists in a dictionary or not.
The program takes a dictionary and checks if a given key exists in a dictionary or not.
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.
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!")
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.
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.
- Check Python Books
- Apply for Programming Internship
- Check Information Technology Books
- Practice Programming MCQs
- Apply for Python Internship