KeyError: 'name'
What it means
You asked a dictionary for a key it does not have. The message shows the missing key exactly as you wrote it, so check its spelling, capital letters and type. Use .get() or in when a key might be missing.
1. The key is not in the dictionary
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> KeyError: 'name'
The fix
unknown 31
.get() returns a default, or None, when the key is missing. Test with in when you need to do something different for a missing key.
2. A typo or different capital letters in the key
This raises the error
Traceback (most recent call last): File "<exec>", line 3, in <module> KeyError: 'Apple'
The fix
1.2 ['apple', 'banana']
Keys must match exactly, so 'Apple' and 'apple' are different keys. Making the text lowercase, and printing the real keys, finds the mismatch quickly.
3. Counting with a key that is not there yet
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> KeyError: 'red'
The fix
{'red': 2, 'blue': 1}
Counter({'red': 2, 'blue': 1})counts[w] += 1 reads the old count first, and the first time there is none. get(w, 0) starts each count at 0, and Counter does the whole job for you.
When you see this error, check
- Print
list(your_dict)to see which keys really exist. - Check spelling, capital letters and spaces in the key.
- Check the type:
1and'1'are different keys. - Use
.get(key, default),key in dorcollections.defaultdictwhen a key may be missing.
Related errors
All Python errors · How to read a traceback · Step through your code