ProjectStack
python

KeyError

You tried to access a dictionary key that doesn't exist. Python raises KeyError when you use dict['key'] and 'key' isn't in the dictionary.

Common causes

  • Typo in the key name — dictionary keys are case-sensitive and must match exactly
  • The key exists in some data but not in this particular record
  • Accessing a key before it's been added to the dictionary
  • API response or JSON data has a different structure than expected

How to fix it

  1. Use .get() instead of [] to return None instead of raising: value = data.get('key')
  2. Provide a default with .get(): value = data.get('key', 'default_value')
  3. Check if the key exists first: if 'key' in data: value = data['key']
  4. Print the full dictionary to see its actual keys: print(data.keys())

Example

Traceback (most recent call last): File "app.py", line 4, in <module> print(user['email']) KeyError: 'email'

Accessing user['email'] when the user dictionary only has 'name' and 'id' keys

Have a different error?

Paste any error message into the Error Translator to get an instant explanation.