KeyError
KeyError: 'username'
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(user["username"])
KeyError: 'username'What causes this error
A dictionary was accessed with a key that does not exist in it. This happens with bracket notation `d[key]`, `.pop(key)` without a default, or destructuring operations that expect certain keys.
How to fix it
Use `dict.get(key, default)` instead of bracket access to provide a fallback. Check for key existence with `if key in d:` before accessing. Use `collections.defaultdict` for dicts that should auto-create missing entries.
Code that causes this error
user = {"name": "Alice", "email": "[email protected]"}
print(user["username"])Fixed code
user = {"name": "Alice", "email": "[email protected]"}
print(user.get("username", "N/A"))About KeyError
A KeyError is raised when you try to access a dictionary key that does not exist. Dictionaries are one of Python's most-used data structures, and KeyError is the natural guard against accessing missing keys. This error appears when reading from a dict with bracket notation (`d[key]`), when using `.pop()` without a default value on a missing key, and when working with JSON data where expected fields are absent.
There are several Pythonic ways to avoid KeyErrors: the `.get()` method returns a default value (None by default) for missing keys, the `in` operator tests for key existence, `.setdefault()` provides a value and inserts it if the key is missing, and `collections.defaultdict` automatically creates entries for missing keys. The error message includes the key that was not found, which makes debugging straightforward.
Common scenarios
Accessing dictionary keys that were never added or have been deleted
Processing JSON data with missing or optional fields
Using the wrong key name due to typos or case sensitivity
Modifying a dictionary while iterating over it