KeyError in Python: Causes and Fixes with Simple Examples
What is KeyError in Python?
A KeyError in Python occurs when you try to access a dictionary key that does not exist.
In simple words, Python is saying:
“This key is not present in the dictionary.”
This error is very common for beginners and usually appears when working with dictionaries, user input, APIs, and JSON data.
Understanding Dictionaries in Python
A dictionary in Python stores data in key–value pairs.
Example:
student = {
"name": "Rahul",
"age": 20
}
-
Keys must exist to access values
-
If a key is missing, Python raises a KeyError
Common KeyError Message
A typical KeyError message looks like this:
KeyError: 'age'
This message tells us:
-
Python tried to access the key
'age' -
That key does not exist in the dictionary
Example 1: KeyError with Dictionary Access
❌ Incorrect Code
student = {
"name": "Rahul",
"course": "Python"
}
print(student["age"])
❌ Error
KeyError: 'age'
✔ Why this happens
-
The dictionary has no key named
"age" -
Python cannot return a value for a missing key
✔ Correct Code
student = {
"name": "Rahul",
"course": "Python"
}
print(student.get("age"))
Example 2: KeyError with User Input
❌ Incorrect Code
data = {
"username": "admin",
"password": "1234"
}
key = input("Enter key: ")
print(data[key])
If the user enters:
email
❌ Error
KeyError: 'email'
✔ Correct Code
data = {
"username": "admin",
"password": "1234"
}
key = input("Enter key: ")
if key in data:
print(data[key])
else:
print("Key not found")
Example 3: KeyError with Loop
❌ Incorrect Code
marks = {
"math": 90,
"science": 85
}
subjects = ["math", "english"]
for sub in subjects:
print(marks[sub])
❌ Error
KeyError: 'english'
✔ Why this happens
-
"english"key does not exist in the dictionary -
Python fails when accessing it
✔ Correct Code
marks = {
"math": 90,
"science": 85
}
subjects = ["math", "english"]
for sub in subjects:
print(marks.get(sub, "Not available"))
Example 4: KeyError with API or JSON Data
❌ Incorrect Code
response = {
"status": "success",
"data": {
"id": 101
}
}
print(response["data"]["name"])
❌ Error
KeyError: 'name'
✔ Why this happens
-
API response does not contain
"name" -
Python cannot find the key
✔ Correct Code
print(response["data"].get("name", "Name not found"))
How to Debug KeyError Easily
Use these simple techniques:
✔ Print dictionary keys using dict.keys()
✔ Use .get() method
✔ Check user input
✔ Validate API responses
Example:
print(student.keys())
How to Avoid KeyError in Python
-
Always check if a key exists
-
Use
inkeyword -
Use
.get()instead of direct access -
Handle API data carefully
Summary
KeyError in Python occurs when you try to access a dictionary key that does not exist.
Once you understand how dictionaries work, fixing KeyError becomes easy.
This error is common while learning Python - practice is the key
❓ Frequently Asked Questions (FAQ)
Q1: Is KeyError a syntax error?
No, it happens at runtime.
Q2: Can KeyError stop my program?
Yes, unless handled properly.
Q3: Is KeyError common for beginners?
Yes, very common.
📌 Final Tip
Always check for key existence before accessing dictionary values.
Comments
Post a Comment