A KeyError occurs when we try to access a key that does not exist in a dictionary. Since dictionaries store data using key-value pairs, Python raises a KeyError whenever a requested key cannot be found. Understanding why this error occurs and how to handle it properly helps in writing more reliable programs.
data = { "name": "John",
"age": 25 }
print(data["city"])
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
KeyError: 'city'
Explanation: data["city"] searches for the key "city" in the dictionary. Since that key is not present, Python raises a KeyError.
Common Causes of KeyError
1. Incorrect Key Name: Key names in dictionaries are case-sensitive. Using the wrong spelling or letter case can result in a KeyError.
data = {"Name": "John"}
print(data["name"])
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
KeyError: 'name'
Explanation: dictionary contains the key "Name" with an uppercase N, but "name" is accessed. Since both keys are treated differently, Python raises a KeyError.
2. Accessing Nested Keys Without Verification: A KeyError can also occur when accessing nested dictionaries and one of the keys does not exist.
data = {"user": {"name": "John"}}
print(data["user"]["city"])
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
KeyError: 'city'
Explanation: key "user" exists, but the nested key "city" does not. Therefore, Python raises a KeyError.
Handling KeyError
1. Using try-except: A try-except block can be used to handle KeyError gracefully and prevent the program from terminating unexpectedly.
data = { "name": "John",
"age": 25 }
try:
print(data["city"])
except KeyError:
print("Key not found.")
Output
Key not found.
Explanation: statement data["city"] raises a KeyError. Instead of stopping the program, the exception is caught by the except KeyError block and a custom message is displayed.
2. Using get(): get() method safely retrieves values from a dictionary. If the key is missing, it returns None instead of raising a KeyError.
data = { "name": "John",
"age": 25 }
city = data.get("city")
print(city)
Output
None
Explanation: data.get("city") searches for the key "city". Since the key is not available, it returns None rather than raising an exception.
3. Using get() with a Default Value: We can also provide a default value that will be returned when the key is not found.
data = { "name": "John",
"age": 25 }
city = data.get("city", "Not Available")
print(city)
Output
Not Available
Explanation: data.get("city", "Not Available") returns "Not Available" because the key "city" does not exist in the dictionary. This helps avoid KeyError while providing a meaningful fallback value.