Check Whether a Key Exists in a Python Dictionary
Python dictionaries provide fast key-based lookup, and checking whether a key exists is a common operation.
Use the in Operator
The clearest and most idiomatic solution is:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
if "name" in my_dict:
print("The key 'name' exists.")
else:
print("The key 'name' does not exist.")Membership tests on a dictionary check keys by default.
Use get() When You Also Need the Value
dict.get() avoids KeyError when a key is missing:
age = my_dict.get("age")However, this is not always a correct existence test:
my_dict = {"answer": None}
if my_dict.get("answer") is not None:
print("exists")The key exists, but its value is None, so the condition is false. If you must distinguish a missing key from a stored None, use in or a unique sentinel:
missing = object()
value = my_dict.get("answer", missing)
if value is not missing:
print("The key exists.")keys() Is Usually Unnecessary
This works:
if "city" in my_dict.keys():
print("The key exists.")But it is more verbose than:
if "city" in my_dict:
print("The key exists.")Avoid Calling __contains__() Directly
You may also see:
my_dict.__contains__("name")That is the special method behind membership testing, but application code should normally use in because it is clearer and idiomatic.
Conclusion
Use key in dictionary when the question is simply whether a key exists. Use get() when you want a value with a fallback, but remember that None can be a legitimate stored value.