defaultdict
A `defaultdict` is a specialized dictionary in Python that automatically assigns a default value to a key if it has not been set yet. This means that when you try to access or modify a key that doesn't exist, instead of raising a `KeyError`, it creates the key with a default value defined by a function you provide, such as `int`, `list`, or `set`. This feature simplifies code and reduces the need for checking if a key exists before using it.
To use a `defaultdict`, you first import it from the `collections` module. You then create an instance by passing a function that defines the default value. For example, `defaultdict(list)` creates a dictionary where each new key will have an empty list as its default value. This is particularly useful for grouping items or counting occurrences, as it allows for cleaner and more efficient code when handling collections of data.