python / beginner
Snippet
Safe Dictionary Access with .get()
The .get() method is a safer way to retrieve values from a dictionary because it returns 'None' (or a default value) if the key does not exist.
snippet.py
1
2
3
4
5
user = {"name": "Bob"}# Returns None instead of raising a KeyErroremail = user.get("email")print(f"Email: {email}")
Breakdown
1
user = {"name": "Bob"}
Creates a dictionary with one key-value pair.
2
user.get("email")
Attempts to find 'email'. Since it's missing, it returns None without crashing.