HomePythonPython Program to Check if a Key Exists in a Dictionary

Python Program to Check if a Key Exists in a Dictionary

Dictionaries in Python are key-value pairs that provide efficient data storage and retrieval. This program demonstrates how to create a Python program to check whether a given key exists in a dictionary.

Problem Statement

Write a Python program that takes a key and a dictionary as input and determines whether the given key exists in the dictionary or not.

Python Program to Check if a Key Exists in a Dictionary

def key_exists(dictionary, key):
    return key in dictionary

# Input (Creating a dictionary)
sample_dict = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

key_to_check = input("Enter the key to check: ")

# Checking if the key exists
if key_exists(sample_dict, key_to_check):
    print(f"The key '{key_to_check}' exists in the dictionary.")
else:
    print(f"The key '{key_to_check}' does not exist in the dictionary.")

Input / Output

Python Program to Check if a Key Exists in a Dictionary

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...