Python errors / KeyError

KeyError in Python

The dictionary has no such key. Python names the key it looked for after KeyError.

KeyError: 'name'

Check these first

  1. The exact key. Keys have to match exactly: "Ada" and "ada" are different, and so are 1 and "1".
  2. Print the keys. print(data.keys()) shows what the dictionary really holds.
  3. Use get(). data.get(key) gives None, or a default you choose, instead of an error when the key might be missing.

Causes and fixes

1 Spelling and capitals

A key has to be written exactly as it was stored, capital letters included.

Broken
ages = {"ada": 36, "alan": 41}
print(ages["Ada"])
KeyError: 'Ada'
Fixed
ages = {"ada": 36, "alan": 41}
print(ages["ada"])
36

2 A number for a text key

The number 1 and the text "1" are different keys. input() gives text, so convert with int() or str() to match how the keys were stored.

Broken
names = {"1": "one", "2": "two"}
print(names[1])
KeyError: 1
Fixed
names = {"1": "one", "2": "two"}
print(names["1"])
one

3 Adding to a count that doesn't exist yet

counts[word] += 1 reads the old count first, and the first time there isn't one. Start it at 0 with get().

Broken
counts = {}
for word in ["a", "b", "a"]:
    counts[word] += 1
print(counts)
KeyError: 'a'
Fixed
counts = {}
for word in ["a", "b", "a"]:
    counts[word] = counts.get(word, 0) + 1
print(counts)
{'a': 2, 'b': 1}

Still stuck?