DEV Community

nitiwit
nitiwit

Posted on

[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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Checkly

Replace beforeEach/afterEach with Automatic Fixtures in Playwright

  • Avoid repetitive setup/teardown in spec file
  • Use Playwright automatic fixtures for true global hooks
  • Monitor JS exceptions with a custom exceptionLogger fixture
  • Keep your test code clean, DRY, and production-grade

Watch video

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!