When using Python dictionaries (dict), you frequently need to determine if a specific key is registered or if a specific value exists. For example, you might want to check if a specific setting exists in a configuration file or if a specific error code has occurred. In Python, you can perform these checks intuitively and efficiently using the in operator.
This article explains how to check for the existence of “Keys,” “Values,” and “Key-Value Pairs.”
1. Checking for a Key
To check if a specific key exists in a dictionary, use the in operator directly on the dictionary object.
Syntax:
key in dict_variable
Recommended Usage:
# Application configuration dictionary
app_config = {
"version": "1.0.5",
"debug_mode": False,
"max_users": 100
}
# Check if the key "debug_mode" exists
key_to_check = "debug_mode"
is_key_present = key_to_check in app_config
print(f"Does key '{key_to_check}' exist?: {is_key_present}")
# Checking for a non-existent key
if "theme_color" in app_config:
print("Theme color setting found.")
else:
print("No theme color setting.")
Output:
Does key 'debug_mode' exist?: True
No theme color setting.
Note: You do not need to use .keys(). Writing key in app_config.keys() gives the same result, but writing simply key in app_config is more common (Pythonic) and is optimized for speed.
2. Checking for a Value
To check if a specific value is contained in a dictionary, use the .values() method to get a list (view) of values, and then use the in operator on it.
Syntax:
value in dict_variable.values()
# Dictionary of User IDs and Statuses
user_statuses = {
"user_001": "active",
"user_002": "inactive",
"user_003": "banned"
}
# Check if there is any "banned" user
has_banned_user = "banned" in user_statuses.values()
print(f"Is there a banned user?: {has_banned_user}")
# Check for "pending" status
if "pending" in user_statuses.values():
print("There are pending users.")
else:
print("No pending users.")
Output:
Is there a banned user?: True
No pending users.
Performance Note: Key searches (key in d) are almost instantaneous regardless of dictionary size (hash search). However, value searches (val in d.values()) must check every value in the dictionary, so processing time can increase proportionally to the amount of data.
3. Checking for Key-Value Pairs (Items)
To check if a specific combination of “Key” and “Value” exists, use the .items() method. Since .items() contains tuples of (key, value), you specify the search target as a tuple.
Syntax:
(key, value) in dict_variable.items()
# Product Inventory
inventory = {
"apple": 50,
"banana": 0,
"orange": 20
}
# Check if "banana" is out of stock (0)
target_pair = ("banana", 0)
is_out_of_stock = target_pair in inventory.items()
print(f"Is banana out of stock(0)?: {is_out_of_stock}")
# Check if "apple" stock is 100 (Actually 50, so False)
if ("apple", 100) in inventory.items():
print("Apple stock is 100.")
else:
print("Apple stock is not 100.")
Output:
Is banana out of stock(0)?: True
Apple stock is not 100.
Summary
Choose the appropriate method depending on what you want to check.
- Check Key:
if key in d:(Fastest and most common) - Check Value:
if value in d.values(): - Check Pair:
if (key, value) in d.items():
Using these properly allows you to prevent errors (like KeyError) and write safe code.
