How to check if a key exists in a dict in Python
Use `key in dict`. It's O(1) and never raises. Avoid dict.has_key() — removed in Python 3.
user = {"name": "Alice", "age": 30}
if "name" in user:
print(user["name"])
if "email" not in user:
print("no email set")The `in` operator on a dict checks the KEYS (not the values). It's O(1) average-case because dicts are hash tables. Never wrap it in a try/except KeyError just to check existence — `in` is both faster and clearer.
A useful pattern: dict.get(key, default) returns the value if the key exists or a default otherwise. It replaces the `if k in d: return d[k] else: return default` pattern with a one-liner.
To check for a value (not a key) use `x in dict.values()` — but this is O(n) since values aren't indexed.
Variations
.get() with default
user = {"name": "Alice"}
email = user.get("email", "unknown@example.com")The most-common alternative to the `in` check.
Check for a value
if "Alice" in user.values():
print("someone is Alice")O(n) — every value is compared.
Multiple keys at once
required = {"name", "email", "age"}
missing = required - user.keys()
if missing:
print("missing:", missing)dict.keys() is a set-like view — supports set ops.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.