"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > [python] defaultdict

[python] defaultdict

Published on 2024-07-30
Browse:529

[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 "", line 1, in 
KeyError: 'three'

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
Release Statement This article is reproduced at: https://dev.to/blackdead263/python-defaultdict-1ndg?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3