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.
What KeyError means
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] += 1fails the first time a word appears. - Text against a number. The key
"7"is not the key7.
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.
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.
chat = ["gg", "lol", "gg", "pog", "gg"]
counts = {}
for emote in chat:
counts[emote] += 1
print(counts)