Python KeyError: meaning and fix

KeyError: You asked a dictionary for a key it does not have.

Code that causes it

scores = {"국어": 90}
print(scores["영어"])
Open in the runner

The key is spelled differently or uses different case. You read a key you never added.

Check with in first. If a missing key is fine, read it with get().

How to fix it

scores = {"국어": 90}
print(scores.get("영어", 0))
Open in the runner

Why it happens

A dictionary finds a value by its key. With no such key, there is nothing to hand back, so it stops.

The official docs are in English. See it in the official Python docs

Back to the runnerMore errors