Python Error

Fix: KeyError when accessing a dictionary key

Exact message

KeyError: 'username'

Quick answer

KeyError means you tried to access a dictionary key that does not exist. Use dict.get(key, default) if the key is optional, or check 'key in dict' first if you need to distinguish missing from present-but-None.

Why this error happens

Dictionaries raise KeyError when the key is not present, unlike lists which raise IndexError. This is intentional: silent None returns would hide bugs. Keys are case-sensitive and must match exactly — 'Username' and 'username' are different keys.

Example: Wrong vs Right

Wrong

user = {"name": "samrat"}
print(user["username"])
# KeyError: 'username'

Right

user = {"name": "samrat"}

# Option 1: .get() with default
print(user.get("username", "guest"))

# Option 2: check first (when you need to distinguish missing)
if "username" in user:
    print(user["username"])
else:
    print("no username key")

# Option 3: defaultdict
from collections import defaultdict
counts = defaultdict(int)
counts["missing"] += 1  # works, defaults to 0

How to fix it (step by step)

  1. Print list(your_dict.keys()) to see the actual keys
  2. Check for case mismatch — keys are case-sensitive
  3. Use .get(key, default) for optional keys
  4. For nested dicts, chain .get() carefully or use try/except KeyError

Frequently asked questions

What is the difference between .get() and []?

[] raises KeyError if the key is missing. .get() returns None (or a specified default). Use [] when the key must exist, .get() when it may not.

How do I safely access nested keys?

Use functools.reduce with .get, or write a helper. In Python 3.11+, try the new sqlite3-style access patterns or use a small recursion.

Why not use setdefault?

setdefault mutates the dict, which can surprise you. .get() is read-only. Prefer .get() unless you specifically want to insert a default.

Related Python errors

Need a fix for a different error?

Use the free to paste any traceback and get an AI-suggested fix in seconds.

Want an AI with memory for your project?

MonsterX AI remembers your codebase across chats.