Practical Use Cases for defaultdict
The defaultdict
is a versatile data structure that can be used in a variety of scenarios. Here are some practical use cases for the defaultdict
:
Counting Occurrences
One common use case for the defaultdict
is counting the occurrences of items in a list or sequence. By using a defaultdict
with a default value of 0
, you can easily keep track of the count for each item.
from collections import defaultdict
## Count the occurrences of words in a sentence
sentence = "the quick brown fox jumps over the lazy dog"
word_count = defaultdict(int)
for word in sentence.split():
word_count[word] += 1
print(dict(word_count))
Output:
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
Grouping Data
Another common use case for the defaultdict
is grouping data based on a key. By using a defaultdict
with a default value of an empty list or set, you can easily append values to the corresponding list or set.
from collections import defaultdict
## Group students by their grades
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"},
{"name": "David", "grade": "C"},
{"name": "Eve", "grade": "B"}
]
grade_groups = defaultdict(list)
for student in students:
grade_groups[student["grade"]].append(student["name"])
print(dict(grade_groups))
Output:
{'A': ['Alice', 'Charlie'], 'B': ['Bob', 'Eve'], 'C': ['David']}
Building Trees and Nested Structures
The defaultdict
can also be used to build tree-like data structures or nested dictionaries. By using a defaultdict
with a default value of another defaultdict
, you can create a hierarchical data structure that can be easily traversed and manipulated.
from collections import defaultdict
## Build a nested dictionary
data = defaultdict(lambda: defaultdict(int))
data["fruits"]["apples"] = 5
data["fruits"]["bananas"] = 3
data["vegetables"]["carrots"] = 10
data["vegetables"]["broccoli"] = 7
print(dict(data))
Output:
{'fruits': {'apples': 5, 'bananas': 3}, 'vegetables': {'carrots': 10, 'broccoli': 7}}
These are just a few examples of the practical use cases for the defaultdict
in Python. By leveraging its ability to provide default values for missing keys, you can write more concise and robust code that handles edge cases more gracefully.