0
0
PythonConceptBeginner · 3 min read

What is defaultdict in Python: Simple Explanation and Usage

defaultdict is a subclass of Python's built-in dict that provides a default value for missing keys automatically. It simplifies code by avoiding key errors and the need to check if a key exists before adding or accessing values.
⚙️

How It Works

Imagine you have a box where you keep items labeled by names. Normally, if you ask for an item that isn't in the box, you get an error or nothing. A defaultdict is like a magic box that automatically creates a new empty item whenever you ask for a label that doesn't exist yet.

Technically, defaultdict takes a function called a factory that tells it what kind of default value to create when a new key is accessed. For example, if you use list as the factory, it will create an empty list for any new key. This means you can add items to that list without checking if the key was there before.

This behavior helps avoid common errors and makes your code cleaner and easier to read.

💻

Example

This example shows how defaultdict automatically creates a list for new keys, so you can append values without checking if the key exists.

python
from collections import defaultdict

# Create a defaultdict with list as the default factory
colors = defaultdict(list)

# Add colors to fruits
colors['apple'].append('red')
colors['banana'].append('yellow')
colors['apple'].append('green')

print(colors)
Output
defaultdict(<class 'list'>, {'apple': ['red', 'green'], 'banana': ['yellow']})
🎯

When to Use

Use defaultdict when you want to group or collect items under keys without writing extra code to check if the key exists. It is perfect for counting, grouping, or building collections like lists, sets, or counters.

For example, if you want to count how many times each word appears in a text, defaultdict(int) will start each count at zero automatically. Or if you want to group students by their classes, defaultdict(list) lets you add students to each class easily.

Key Points

  • defaultdict is a dictionary that provides default values for missing keys.
  • It requires a factory function to specify the default value type.
  • Common factories include list, int, and set.
  • It helps avoid KeyError and simplifies code for grouping or counting.
  • It is part of the collections module and easy to import.

Key Takeaways

defaultdict automatically creates default values for missing keys to avoid errors.
It simplifies code when grouping, counting, or collecting items under keys.
You must provide a factory function like list or int to define the default value type.
It is part of Python's collections module and easy to use.
Using defaultdict makes your code cleaner and more readable.