Brainlag
  1. Library
  2. Debugging
  3. Python

KeyErrorWhat is a KeyError?

A KeyError means you looked up a dictionary key that is not there. A typo, a different capital letter, or a key that was never added.

Python5 min

What KeyError means

Output
KeyError: 'chips'

The message is just the key that was missing. prices["chips"] only works if "chips" was put into prices earlier. Unlike a list, a dict has no "nearby" item to fall back on.

The usual causes:

  • A typo or a capital. "Chips" and "chips" are different keys.
  • A key that was never added. Counting with counts[word] += 1 fails the first time a word appears.
  • Text against a number. The key "7" is not the key 7.

How to find it

The last line shows the missing key exactly, quotes and all. Print the dict's keys just above the failing line with print(list(d.keys())) and compare. If the key should be optional, read it with d.get(key, default) or check with if key in d: first.

Run it: an item that is not on the menu

Press Run and read the error from the bottom up.

main.py to run
prices = {"cola": 0.90, "crisps": 1.20}
print(prices["cola"])
print(prices["chips"])

The word counter that crashes on the first word

This should count how often each emote appears in the chat. Fix the counting line.

exercise_1.py to run
chat = ["gg", "lol", "gg", "pog", "gg"]
counts = {}
for emote in chat:
    counts[emote] += 1
print(counts)

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.