Skip to main content

How to check if a key exists in a dictionary in Python

How to check if a key exists in a dictionary in Python.

Here's a step-by-step tutorial on how to check if a key exists in a dictionary in Python:

Step 1: Create a dictionary To begin, you need to create a dictionary. In Python, you can create a dictionary by enclosing comma-separated key-value pairs within curly braces {}. For example, let's create a dictionary called my_dict:

my_dict = {"name": "John", "age": 25, "city": "New York"}

Step 2: Use the in operator The in operator is used to check if a key exists in a dictionary. You can use it in combination with the dictionary name and the key you want to check. Here's the syntax:

if key in dictionary:
# Key exists
else:
# Key does not exist

Step 3: Check if a key exists Now, let's check if a key exists in the my_dict dictionary. We'll use the in operator to check for the key "age":

if "age" in my_dict:
print("Key 'age' exists in the dictionary.")
else:
print("Key 'age' does not exist in the dictionary.")

If the key "age" exists in the dictionary, it will print "Key 'age' exists in the dictionary." Otherwise, it will print "Key 'age' does not exist in the dictionary."

Step 4: Example with a non-existent key Let's now check for a key that doesn't exist in the dictionary. We'll use the key "gender" for this example:

if "gender" in my_dict:
print("Key 'gender' exists in the dictionary.")
else:
print("Key 'gender' does not exist in the dictionary.")

Since the key "gender" doesn't exist in the dictionary, it will print "Key 'gender' does not exist in the dictionary."

Step 5: Using the get() method (optional) Python dictionaries also provide a get() method that can be used to check if a key exists in a dictionary. The get() method returns the value associated with the key if it exists, or a default value if the key is not found. Here's an example:

value = my_dict.get("name")
if value is not None:
print("Key 'name' exists in the dictionary.")
else:
print("Key 'name' does not exist in the dictionary.")

In this example, the get() method is used to retrieve the value associated with the key "name". If the key exists, it will print "Key 'name' exists in the dictionary." Otherwise, it will print "Key 'name' does not exist in the dictionary."

That's it! You now know how to check if a key exists in a dictionary in Python.