Menu

Python KeyError Explained: Why It Happens and How to Fix It
📰

Python KeyError Explained: Why It Happens and How to Fix It

DEV Community: beginners·Lavkush Kumar·6 days ago
#TLmotGKd
#devtobeginners#devto#dev#python#missing
Reading 0:00
15s threshold

Originally published on CodingCush .

A Python KeyError means your code asked a dictionary for a key that does not exist in that dictionary. Python cannot guess what you wanted, so it stops the program and shows the missing key by name. It is one of the most common errors beginners meet, and the good news is that it is also one of the easiest to understand and fix once you know why it happens.

What a KeyError Looks Like

Here is the smallest example that causes the error. We create a dictionary for a student, then ask for a key that was never added.

student = {"name": "Priya", "age": 21}

print(student["city"])

Enter fullscreen mode

Exit fullscreen mode

Python replies with a short message like this:

Traceback (most recent call last): File "main.py", line 3, in <module> print(student["city"]) KeyError: 'city'

Enter fullscreen mode

Exit fullscreen mode

Read that last line carefully. Python is telling you the exact key it could not find, in this case city.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.