Python Program to Check if a Key is Already Present in a Dictionary Ad Sponsored

ⓘ Sponsored by

In a dictionary in Python, a key is a unique identifier used to access a specific value. Each key in the dictionary maps to a corresponding value, and the key-value pairs are stored together as one item.

Keys in a Python dictionary must be immutable, meaning they cannot be changed once they are assigned.

Python Code :

The below Python program checks if a key is already present in a dictionary:

# Define a dictionary
my_dict = {'apple': 5, 'banana': 2, 'orange': 7}

# Take input key from user
key = input("Enter a key to check if it's present in the dictionary: ")

# Check if key is present in the dictionary
if key in my_dict:
    print(f"{key} is already present in the dictionary.")
    print(f"{key} is not present in the dictionary.")

In this program, we first define a dictionary called my_dict that contains some key-value pairs. We then take input from the user for the key to be checked. We use the in operator to check if the key is already present in the dictionary. If the key is present, we print a message saying so. Otherwise, we print a message saying that the key is not present in the dictionary. Ad Sponsored

ⓘ Sponsored by