Check whether a dictionary contains a key in Python
Use in for key membership, get for a value with a fallback, and a unique sentinel when a stored None must remain distinct from a missing key.
Use key in mapping to test whether a dictionary contains a key. It checks keys, not values.
mapping = {"a": 1, "b": 2, "c": 3}
if "a" in mapping:
print("The key exists")
For ordinary built-in dictionaries, membership lookup is expected constant time under typical hashing behavior. It is not an unconditional worst-case guarantee for arbitrary keys or custom mappings.
Retrieve a value with a fallback
print(mapping.get("a")) # 1
print(mapping.get("missing")) # None
print(mapping.get("missing", 0)) # 0
get() does not insert the missing key. A fallback of None is ambiguous when None is also a valid stored value.
Distinguish missing from None
mapping = {"a": None}
missing = object()
value = mapping.get("a", missing)
print(value is missing) # False
print("a" in mapping) # True
Use an identity comparison with a unique sentinel rather than treating all false values as missing. The same distinction matters for 0, empty strings, and empty containers.
Initialize a missing entry
mapping = {"a": 1}
value = mapping.setdefault("d", 4)
print(value) # 4
print(mapping) # {'a': 1, 'd': 4}
setdefault() returns an existing value unchanged; otherwise it inserts the default. Its default argument expression is still evaluated before the call, even when the key exists. Do not use it merely to check membership when mutation is unwanted.
FAQ
How do I check values instead? value in mapping.values() searches the values and generally requires a linear scan. Use a separate index when repeated value lookups justify one.
How do I check a nested dictionary? Confirm the intermediate object's type as well as the key:
from collections.abc import Mapping
nested = {"a": {"b": 2}}
inner = nested.get("a")
if isinstance(inner, Mapping) and "b" in inner:
print(inner["b"])
nested.get("a", {}).get("b") fails when a exists but holds None or another nonmapping value. Likewise, catching only KeyError does not cover a wrong intermediate type.
What happened to has_key()? It was a Python 2 method and is absent in Python 3. Use membership syntax.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan