A KeyError occurs when attempting to access a dictionary key that does not exist.
data = {"name": "Alice"}
print(data["age"]) # KeyErrorThe key "age" is not present in the dictionary.
In real-world applications, a KeyError commonly occurs when:
- Handling external API responses.
- Parsing JSON data.
- Processing dynamic user input.
- Assuming optional fields are always present.
Example:
response = {
"user": {
"name": "Alice"
}
}
age = response["user"]["age"] # KeyErrorIf the external system does not guarantee the "age" field, direct indexing becomes unsafe.
if "age" in response["user"]:
age = response["user"]["age"]age = response["user"].get("age")This returns None if the key is missing.
You may also provide a default value:
age = response["user"].get("age", 0)from collections import defaultdict
counter = defaultdict(int)
counter["a"] += 1defaultdict is useful for counting or grouping patterns.
If the goal is safe lookup rather than aggregation, dict.get() is usually clearer and more explicit.