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