[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>”, li…


This content originally appeared on DEV Community and was authored by Adel Bordbari

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'

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


This content originally appeared on DEV Community and was authored by Adel Bordbari


Print Share Comment Cite Upload Translate Updates
APA

Adel Bordbari | Sciencx (2024-07-21T07:05:57+00:00) [python] defaultdict. Retrieved from https://www.scien.cx/2024/07/21/python-defaultdict/

MLA
" » [python] defaultdict." Adel Bordbari | Sciencx - Sunday July 21, 2024, https://www.scien.cx/2024/07/21/python-defaultdict/
HARVARD
Adel Bordbari | Sciencx Sunday July 21, 2024 » [python] defaultdict., viewed ,<https://www.scien.cx/2024/07/21/python-defaultdict/>
VANCOUVER
Adel Bordbari | Sciencx - » [python] defaultdict. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/21/python-defaultdict/
CHICAGO
" » [python] defaultdict." Adel Bordbari | Sciencx - Accessed . https://www.scien.cx/2024/07/21/python-defaultdict/
IEEE
" » [python] defaultdict." Adel Bordbari | Sciencx [Online]. Available: https://www.scien.cx/2024/07/21/python-defaultdict/. [Accessed: ]
rf:citation
» [python] defaultdict | Adel Bordbari | Sciencx | https://www.scien.cx/2024/07/21/python-defaultdict/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.