Home > Backend Development > Python Tutorial > How to Return a Default Value for Missing Dictionary Keys in Python?

How to Return a Default Value for Missing Dictionary Keys in Python?

Patricia Arquette
Release: 2024-11-17 21:27:02
Original
476 people have browsed it

How to Return a Default Value for Missing Dictionary Keys in Python?

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:

  • The key you're interested in
  • A default value to return if the key doesn't exist (optional)

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template