← Back to Error Guide
KeyError

How to Fix KeyError

Understanding and resolving KeyError in Python

What is KeyError?

A KeyError happens when you try to access a key in a dictionary that doesn't exist.

Common Causes

Common causes of this error...

How to Fix

Wrong Code

# Code that causes the error
d = {'name': 'Alice'}
print(d['age'])

Correct Code

# Fixed code
d = {'name': 'Alice'}
print(d.get('age', 'Not available'))

More Python Error Guides