collections.defaultdict
Create a dictionary that adds a missing key with a default value when you access it.
Python 3.13
collections.defaultdict([default_factory])Parameters
- default_factoryCallable | Noneoptional
- A function without arguments that creates the default value, such as list or int; with None, a missing key raises KeyError.
Return value
A defaultdict object, a dictionary subclass.
Examples
Grouping words by first letter
Python 3.13
from collections import defaultdict
groups = defaultdict(list)
for word in ['apple', 'avocado', 'banana']:
groups[word[0]].append(word)
print(dict(groups)){'a': ['apple', 'avocado'], 'b': ['banana']}Counting letters with a default of 0
Python 3.13
from collections import defaultdict
counts = defaultdict(int)
for letter in 'hello':
counts[letter] += 1
print(counts['l'], counts['z'])2 0
Details
Pass the function itself without parentheses: defaultdict(list), not defaultdict([]). A key is added only on access with d[key]; get() and in do not add it.
