KeyError: key not found in dictionary
Quick summary
You used dict[key] with a key that is not in the dictionary — Python raises KeyError with the missing key as the argument.
Why this happens
The key was never inserted into the dictionary, or was deleted before the access attempt
The key type or value does not match what was stored — e.g., string '1' vs integer 1
The dictionary was expected to have default entries that were not initialized before the access
Minimal example
config = {'host': 'localhost', 'port': 8080}
print(config['database']) # KeyError: 'database'config = {'host': 'localhost', 'port': 8080}
print(config.get('database', 'default_db')) # prints 'default_db'Using dict.get() with a default value returns the default when the key is missing, avoiding KeyError entirely.
How to diagnose
Print the dictionary keys with dict.keys() and compare with the key you are trying to access
Check the type of the key with type(key) — a string key and integer key are different in Python
Use a debugger or print statements to trace where the dictionary is populated and what keys are added
How to fix
Use dict.get(key, default) to return a default value instead of raising KeyError when the key is missing
Use collections.defaultdict to automatically create entries with a default value for missing keys
Check key membership with 'key in dict' before accessing, and insert a default if the key is absent
How to prevent
Use dict.get() with a default value for all dictionary accesses where the key might not exist
Initialize dictionaries with all expected keys and default values before use in lookup-heavy code
Related Resources
Related Glossary
Related Lessons
- Dictionaries
Learn about dictionaries.