Home > Backend Development > Python Tutorial > How to Get Dictionary Values or Return a Default Value When a Key is Missing?

How to Get Dictionary Values or Return a Default Value When a Key is Missing?

Linda Hamilton
Release: 2024-12-05 06:47:11
Original
1022 people have browsed it

How to Get Dictionary Values or Return a Default Value When a Key is Missing?

Get Dictionary Value or Return Default Value on Key Absence

Retrieving dictionary values by key is straightforward in Python, but attempting to access non-existent keys raises a KeyError exception. For a more explicit and user-friendly approach, we can utilize the dict.get() method.

dict.get() allows specifying a fallback value to return in case the sought key doesn't exist. If the key is present, the associated value is returned. Otherwise, the provided default value is returned instead of raising an exception.

The syntax is:

value = d.get(key)
Copy after login

By default, value will be None if the key doesn't exist. To specify a custom default value, use the following syntax:

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

In this example, "empty" would be returned if the key is absent in the dictionary d.

The above is the detailed content of How to Get Dictionary Values or Return a Default Value When a Key is Missing?. 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