September 2026
1051 pages
35h 4m
English
The defaultdict data type is a generalization of the Counter data type described in the previous section. For a Counter instance, when a nonexistent key k is accessed, the key-value pair {k: 0} is automatically added to the dictionary. A defaultdict instance in this case adds the key-value pair {k: x()}, where x represents any data type.
The value data type is passed during the instantiation process. The defaultdict can then be used like a normal dictionary.
For example, if you want to group the words of a text according to their length, you can do this using the basic dict data type as follows:
>>> t = "if for else while elif with not and or try except">>> d = {}>>> for word in t.split(" "):... if
Read now
Unlock full access