[python] defaultdict

PHPz
Release: 2024-07-21 20:30:41
Original
479 people have browsed it

[python] defaultdict

normal dict raises Keyerror after querying keys that don't exist

>>> from collections import defaultdict
>>> my_dict = {"one": 1, "two": 2}
>>> my_dict["three"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'three'
Copy after login

but by using a lamda in a deafultdict we can set default values for undefined keys

# create a default dict, from a dict
>>> my_def_dict = defaultdict(lambda: -1, my_dict)
>>> my_def_dict["zero"]
-1

# create an empty default dict
>>> empty_def_dict = defaultdict(lambda: true)
# add key-value pairs here
Copy after login

The above is the detailed content of [python] defaultdict. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!