← All Python errors

Python error explained

KeyError: what it means and how to fix it

That key is not in the dictionary.

The message

KeyError: 'Ava'

What it means

Square brackets on a dictionary demand that the key exists. If it does not, Python raises a KeyError naming the missing key. Keys are case sensitive too.

Common causes

  • A typo or different capitals in the key
  • Counting with counts[word] += 1 before the word has been added
  • Expecting data that is not there

Example that raises it

votes = ["Ava", "Ben", "Ava", "Cal", "Ava"]
counts = {}
for name in votes:
    counts[name] += 1
print(counts)

The fix

votes = ["Ava", "Ben", "Ava", "Cal", "Ava"]
counts = {}
for name in votes:
    counts[name] = counts.get(name, 0) + 1
print(counts)

Tip: dict.get(key, default) returns the default instead of crashing, and "key in my_dict" lets you check first.

Fix the broken version yourself in the editor on this page. It runs real Python in your browser.

Start the free lessons More Python errors