TryBugHunt

KeyError: 'key' in a Python dictionary

KeyError: 'key' in a Python dictionary in Python means 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.

PythonPattern: Null and undefined errors

How do I fix KeyError: 'key' in a Python dictionary?

KeyError in Python means you looked up a dictionary key that does not exist, using d[key]. The message shows the exact missing key. Compare it with list(d.keys()), watching for spaces, case and type, like '1' versus 1. Use d.get(key, default) when a missing key is normal, and collections.Counter or d.get(w, 0) + 1 when counting.

  1. 1. Print the real keysPrint list(d.keys()) just before the failing line and compare with the key shown in the error.
  2. 2. Check key typeQuotes in the message mean a string key. JSON keys are always strings, so data[1] fails where data["1"] works.
  3. 3. Check spaces and caseKeys from CSV headers or user input often have trailing spaces or different case. Strip and lower them once.

What does KeyError: 'key' in a Python dictionary mean?

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.

Why does KeyError: 'key' in a Python dictionary happen?

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

lookup_cached_score('{"1": 95}', 1) raises KeyError: 1.

import json

def lookup_cached_score(cache_json, user_id):
    data = json.loads(cache_json)
    return data[user_id]
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this error. Find the bug and fix it, no install and 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.