Home > Backend Development > Python Tutorial > How to Safely Retrieve Dictionary Values with a Default When a Key Doesn\'t Exist?

How to Safely Retrieve Dictionary Values with a Default When a Key Doesn\'t Exist?

Susan Sarandon
Release: 2024-11-15 19:22:03
Original
426 people have browsed it

How to Safely Retrieve Dictionary Values with a Default When a Key Doesn't Exist?

Retrieving Dictionary Value with Default on Non-Existence

When accessing a dictionary, attempting to retrieve a value for a non-existent key results in a KeyError. To handle this scenario gracefully, a method is required to safely retrieve the value or return a default value.

The solution lies within the get() method of the dictionary. By employing this method, you can specify a default value to be returned when the key is absent:

value = d.get(key)
Copy after login

If the key exists in the dictionary, it returns the corresponding value. Otherwise, it returns None.

Furthermore, you can provide a custom default value to be returned:

value = d.get(key, "empty")
Copy after login

In this example, if the key is not found in the dictionary, the string "empty" will be returned.

The above is the detailed content of How to Safely Retrieve Dictionary Values with a Default When a Key Doesn't Exist?. 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