BugHunt

KeyError: 'key' in a Python dictionary

You looked up a key the dictionary does not have. The key in the message is the exact one that was missing — compare it character by character with what is really there.

PythonNull and undefined errors

What it means

Square-bracket lookup on a dict demands that the key exists, and raises KeyError with the missing key when it does not. That is deliberate: Python would rather stop than hand you a silent None. The message prints the key with repr(), so quotes tell you its type — KeyError: '1' is a string, KeyError: 1 is an int.

Common causes

1. Counting without initialising the key

counts[w] += 1 reads counts[w] first, and on the first sighting of a word there is nothing to read.

Breaks

counts = {}
for w in words:
    counts[w] += 1

Works

from collections import Counter
counts = Counter(words)

# or, by hand:
counts[w] = counts.get(w, 0) + 1

2. The key is there, but as a different type

JSON object keys are always strings. After json.loads, data[1] fails even though the file plainly has a "1".

Breaks

data = json.loads('{"1": "Ada"}')
name = data[1]

Works

name = data["1"]
# or convert once: data = {int(k): v for k, v in data.items()}

3. Whitespace or capitalisation in the key

Keys built from user input or CSV headers often carry a trailing space or different case. 'Name ' and 'name' are different keys.

Breaks

row = {"Name ": "Ada"}
print(row["Name"])

Works

row = {k.strip().lower(): v for k, v in row.items()}
print(row["name"])

4. An optional field that some records lack

The code works on the first records you tested and fails on the one without the field.

Breaks

for user in users:
    print(user["middle_name"])

Works

for user in users:
    print(user.get("middle_name", ""))

How to find it in your own code

Print list(d.keys()) right before the failing line and compare with the key in the message, including quotes and spaces. Use d[key] when a missing key really is a bug, and d.get(key, default) when missing is a normal case — choosing deliberately is the whole fix. The same error from pandas (df["col"]) means a column name mismatch; print df.columns.

Try it: fix this bug

easy

Looking up a key that isn't in the config crashes with KeyError instead of returning "default".

def get_setting(config, key):
    return config[key]
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this exact error. Find the bug and fix it in your browser — no install, no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors