How to Check if a Key Exists in a Dictionary using Python
In this tutorial, we’ll learn how to program "How to Check if a Key Exists in a Dictionary Using Python." The objective is to safely check if a key currently exists in a dictionary. This tutorial will demonstrate the process of verifying whether a specific key is present in a dictionary. A sample program will be provided to guide you through the implementation. So, let’s get started!
This topic is simple to understand. Just follow the instructions I provide, and you’ll be able to complete it with ease. The program I’ll demonstrate will show you the correct way to check if a key exists in a dictionary. So, let’s start coding!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
- while True:
- print("\n================= Check if a Key Exists in a Dictionary =================\n\n")
- print(d)
- print("\n")
- key = input("Enter a key: ")
- if key in d:
- print("Key already exist.")
- else:
- print("Key does not exist.")
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This program checks if a specified key exists in a dictionary. It starts with a predefined dictionary d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}. The user is prompted to input a key. If the key exists in the dictionary, the program outputs "Key already exists." Otherwise, it outputs "Key does not exist." The process repeats in a loop until the user chooses to exit.
Output:

There you have it we successfully created How to Check if a Key Exists in a Dictionary using Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language