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.
  1. d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
  2.  
  3.  
  4. while True:
  5.     print("\n================= Check if a Key Exists in a Dictionary =================\n\n")
  6.     print(d)
  7.     print("\n")
  8.     key = input("Enter a key: ")
  9.     if key in d:
  10.         print("Key already exist.")
  11.     else:
  12.         print("Key does not exist.")
  13.  
  14.     opt = input("\nDo you want to try again?(yes/no): ")
  15.  
  16.     if opt.lower() == 'yes':
  17.         ret=False
  18.     elif opt.lower() == 'no':
  19.         ret=True
  20.         print("Exiting program....")
  21.     else:
  22.         print("Please enter yes/no:")
  23.         break
  24.  
  25.     if ret == False:
  26.         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

Python Tutorials

Add new comment