πŸ”§ Error Fixes

Fix: Python KeyError


KeyError: 'username'

You’re trying to access a dictionary key that doesn’t exist.

Fix 1: Use .get() with a default

# ❌ Crashes if key is missing
name = data['username']

# βœ… Returns None if missing
name = data.get('username')

# βœ… Returns a default value
name = data.get('username', 'anonymous')

Fix 2: Check if the key exists

if 'username' in data:
    name = data['username']

Fix 3: Use try/except

try:
    name = data['username']
except KeyError:
    name = 'anonymous'

Fix 4: Check your data shape

The key might be named differently than you expect:

# Print all available keys
print(data.keys())

# Common issue: API returns different key names
# You expect 'username' but it's actually 'user_name' or 'user'

Fix 5: Nested dictionaries

# ❌ Crashes if 'user' or 'profile' is missing
name = data['user']['profile']['name']

# βœ… Chain .get() calls
name = data.get('user', {}).get('profile', {}).get('name', 'unknown')

See also: Python cheat sheet | Python NoneType not subscriptable fix