August 2019
Beginner
482 pages
12h 56m
English
defaultdict lives in the built-in collections module. It has a default value set upon creation, and if a missing key is passed, it will return this default value instead of raising KeyError. While this behavior can be achieved through the get method of an ordinary dictionary, defaultdict performs twice as quickly as those that have missing values. In the following snippet, we define a dictionary that will return an empty string if the key value is missing:
from collections import defaultdictd = defaultdict(str) # returns empty string as default valued['name'] = 'John'
Now, let's get the values out:
>>> d['name']John>>>d['surname']>>> ''
As you can see, defaultdict does not raise KeyError if the key is missing. Instead, it passes ...