logo
Python Data Structures - Interview Questions and Answers
What is the purpose of the defaultdict in Python?
Purpose of defaultdict in Python

defaultdict is a subclass of Python’s built-in dict that automatically provides a default value for missing keys, preventing KeyError. It’s part of the collections module.


1. Why Use defaultdict?
  • Avoids KeyError when accessing missing keys.
  • Automatically assigns a default value to new keys.
  • Simplifies code, especially when handling nested structures like lists or sets.

2. Basic Usage of defaultdict
Without defaultdict (Using Normal dict)
my_dict = {}
my_dict["a"].append(1)  # ? KeyError: 'a' (Key does not exist)
With defaultdict (Prevents KeyError)
from collections import defaultdict

# Creates a defaultdict with list as the default factory
my_dict = defaultdict(list)

# No KeyError, automatically initializes 'a' as an empty list
my_dict["a"].append(1)

print(my_dict)  # Output: {'a': [1]}

* No KeyError! defaultdict automatically creates an empty list.


3. Default Factories in defaultdict

You can pass a factory function to specify default values:

Default Factory Example Default Value
list defaultdict(list) [] (Empty list)
int defaultdict(int) 0
set defaultdict(set) set() (Empty set)
str defaultdict(str) '' (Empty string)
lambda: custom_value defaultdict(lambda: 100) 100
Example: Using int to Count Occurrences
word_count = defaultdict(int)
words = ["apple", "banana", "apple", "orange", "banana", "banana"]

for word in words:
    word_count[word] += 1  # No need to check if key exists!

print(word_count)  # Output: {'apple': 2, 'banana': 3, 'orange': 1}

* No need to initialize keys manually!


4. Nested defaultdict (Creating Auto-Nested Dictionaries)

defaultdict can be used to create nested dictionaries without manually initializing sub-dictionaries.

Example : Creating a Nested Dictionary
nested_dict = defaultdict(lambda: defaultdict(int))

nested_dict["A"]["Math"] = 90
nested_dict["A"]["Science"] = 85

print(nested_dict)  
# Output: {'A': {'Math': 90, 'Science': 85}}

* Automatically creates sub-dictionaries when accessing missing keys.


5. When to Use defaultdict vs. dict?
Feature dict defaultdict
Handles missing keys ? No (KeyError) ? Yes (Auto-initialized)
Requires manual initialization ? Yes ? No
Best for Simple lookups Grouping, counting, nesting

When Should You Use defaultdict?

* When grouping elements (defaultdict(list))
* When counting occurrences (defaultdict(int))
* When creating nested dictionaries (defaultdict(lambda: defaultdict(int))