Yesterday we learned how to loop through dictionaries. Today, let’s tackle a common problem: what happens when you try to access a dictionary key that doesn’t exist? This is a frequent source of errors for new programmers.
Consider our user profile dictionary from yesterday. If you try to access a key using square brackets [] and the key isn’t there, your program will crash with a KeyError.
Python
user_profile = {
"username": "alex_py",
"level": 7
}
# This works fine
print(user_profile["username"])
# This will crash the program!
# print(user_profile["last_login"])
# >> KeyError: 'last_login'
This is risky. You can’t always guarantee that a key will be present in a dictionary you are working with, especially if the data comes from an external source like a user or an API.
The Safe and Pythonic Way: .get()
To avoid this crash, Python dictionaries have a wonderful built-in method called .get(). This method provides a safe way to access keys.
If the key exists, .get() will return its value, just like the square bracket notation. But if the key does not exist, instead of raising an error, it will simply return None.
Python
user_profile = {
"username": "alex_py",
"level": 7
}
# Safely access the key
last_login = user_profile.get("last_login")
print(f"Username: {user_profile.get('username')}") # Output: Username: alex_py
print(f"Last Login: {last_login}") # Output: Last Login: None
This prevents your program from stopping unexpectedly.
Providing a Default Value
The .get() method is even more powerful because you can provide a second argument: a default value to return if the key is not found.
Python
user_profile = {
"username": "alex_py",
"level": 7
}
# Provide a default value if the key is missing
active_status = user_profile.get("is_active", False)
print(f"Is Active: {active_status}") # Output: Is Active: False
Using .get() is a fundamental best practice when working with dictionaries. It makes your code more robust and resilient to missing data. That’s it for today!