KeyError in Python
The dictionary has no such key. Python names the key it looked for after KeyError.
Your error
Check these first
- The exact key. Keys have to match exactly:
"Ada"and"ada"are different, and so are1and"1". - Print the keys.
print(data.keys())shows what the dictionary really holds. - Use get().
data.get(key)givesNone, 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.
ages = {"ada": 36, "alan": 41}
print(ages["Ada"])
KeyError: 'Ada'
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.
names = {"1": "one", "2": "two"}
print(names[1])
KeyError: 1
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().
counts = {}
for word in ["a", "b", "a"]:
counts[word] += 1
print(counts)
KeyError: 'a'
counts = {}
for word in ["a", "b", "a"]:
counts[word] = counts.get(word, 0) + 1
print(counts)
{'a': 2, 'b': 1} Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Dictionaries
- Other errors: AttributeError, FileNotFoundError, IndentationError, IndexError, ModuleNotFoundError, NameError, RecursionError, SyntaxError, TypeError, UnboundLocalError, ValueError, ZeroDivisionError