capypad
0 day streak
python / beginner
Snippet

Safe Dictionary Access with .get()

The .get() method is the safest way to access dictionary values. Unlike square brackets, it doesn't raise a KeyError if the key is missing; instead, it returns None or a custom default value you provide.

snippet.py
python
1
2
3
4
5
6
user_data = {"name": "Alice", "role": "Admin"}
 
# Safely access a key that might not exist
email = user_data.get("email", "[email protected]")
 
print(f"User Email: {email}")
Breakdown
1
user_data = {...}
Creates a dictionary with two existing keys: 'name' and 'role'.
2
user_data.get("email", ...)
Attempts to fetch 'email'. Since it's missing, it returns the provided default string.