Returning a Default Value for Missing Dictionary Keys
When accessing a key in a Python dictionary, you encounter a KeyError exception if the key doesn't exist. This behavior can become cumbersome, especially when you prefer to return a default value instead of handling the exception.
Explicit Default Value Retrieval
To explicitly return a default value when searching for a key, you can utilize the dict.get() method. This method takes two arguments:
Example Usage
Here's an example to illustrate how you can use dict.get():
my_dict = {"name": "John", "age": 30} # Retrieve the value for "name" (exists in the dictionary) name = my_dict.get("name") # Returns "John" # Retrieve the value for "occupation" (doesn't exist in the dictionary) occupation = my_dict.get("occupation") # Returns None # Retrieve the value for "occupation" and provide a default value default_occupation = my_dict.get("occupation", "Unemployed") # Returns "Unemployed"
Using dict.get() allows you to explicitly retrieve values, returning a default value if the key doesn't exist, without having to perform additional key existence checks.
The above is the detailed content of How to Return a Default Value for Missing Dictionary Keys in Python?. For more information, please follow other related articles on the PHP Chinese website!