How to check if a key exists in a dictionary in Python
· 1 min read · Updated March 16, 2026 · beginner
python dict dictionaries key
There are three main ways to check if a key exists in a dictionary. Choose based on whether you need the value.
Using the in operator
The cleanest and most Pythonic way:
user = {"name": "Alice", "age": 30, "city": "London"}
if "name" in user:
print("Name found!") # Name found!
This checks keys only, not values. It is the recommended approach.
Using .get()
Returns None (or a default) if the key does not exist:
user = {"name": "Alice", "age": 30}
email = user.get("email")
print(email) # None
# With default
email = user.get("email", "not provided")
print(email) # not provided
Useful when you want the value in one step.
Using try/except
Catching KeyError is faster when keys are usually present:
user = {"name": "Alice", "age": 30}
try:
name = user["name"]
print(f"Found: {name}") # Found: Alice
except KeyError:
print("Key not found")
This avoids the hash lookup twice but is slightly more verbose.
Performance note
All three methods have O(1) average time complexity. The in operator is slightly faster when you only need to check existence since it does not return a value.