Editor

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

Broken
person = {'email': 'ana@example.com', 'age': 31}
print(person['name'])
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
KeyError: 'name'

The fix

Fixed
person = {'email': 'ana@example.com', 'age': 31}
print(person.get('name', 'unknown')) # a default instead of an error
if 'age' in person:
print(person['age'])
Output
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.

Try fixing it yourself in the editor

2. A typo or different capital letters in the key

This raises the error

Broken
prices = {'apple': 1.20, 'banana': 0.50}
item = 'Apple'
print(prices[item])
Output
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
KeyError: 'Apple'

The fix

Fixed
prices = {'apple': 1.20, 'banana': 0.50}
item = 'Apple'
print(prices[item.lower()])
print(list(prices)) # the keys that really exist
Output
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.

Try fixing it yourself in the editor

3. Counting with a key that is not there yet

This raises the error

Broken
words = ['red', 'blue', 'red']
counts = {}
for w in words:
counts[w] += 1
print(counts)
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
KeyError: 'red'

The fix

Fixed
from collections import Counter
words = ['red', 'blue', 'red']
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
print(Counter(words))
Output
{'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.

Try fixing it yourself in the editor

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: 1 and '1' are different keys.
  • Use .get(key, default), key in d or collections.defaultdict when a key may be missing.

All Python errors · How to read a traceback · Step through your code