Counting Grouped Elements with defaultdict
Counting Occurrences of Elements
One of the most common use cases for defaultdict
is counting the occurrences of elements in a collection. Let's say we have a list of items, and we want to count how many times each item appears. We can use a defaultdict
to make this task much easier:
from collections import defaultdict
items = ['apple', 'banana', 'cherry', 'apple', 'banana', 'date']
## Create a defaultdict to count the occurrences
count_dict = defaultdict(int)
for item in items:
count_dict[item] += 1
print(count_dict)
## Output: defaultdict(<class 'int'>, {'apple': 2, 'banana': 2, 'cherry': 1, 'date': 1})
In this example, we initialize a defaultdict
with the default value of int
, which will automatically set the count for a new item to 0
. As we iterate through the items
list, we increment the count for each item in the count_dict
.
Grouping Elements by Key
Another common use case for defaultdict
is grouping elements by a key. For example, let's say we have a list of tuples, where each tuple represents a person and their favorite fruit. We can use a defaultdict
to group the people by their favorite fruit:
from collections import defaultdict
people_fruits = [
('Alice', 'apple'),
('Bob', 'banana'),
('Charlie', 'cherry'),
('David', 'apple'),
('Eve', 'banana'),
('Frank', 'date')
]
## Create a defaultdict to group people by their favorite fruit
fruit_dict = defaultdict(list)
for person, fruit in people_fruits:
fruit_dict[fruit].append(person)
print(fruit_dict)
## Output: defaultdict(<class 'list'>, {'apple': ['Alice', 'David'], 'banana': ['Bob', 'Eve'], 'cherry': ['Charlie'], 'date': ['Frank']})
In this example, we initialize a defaultdict
with the default value of an empty list. As we iterate through the people_fruits
list, we add each person to the list associated with their favorite fruit in the fruit_dict
.
Mermaid Diagram: Counting Grouped Elements with defaultdict
graph TD
A[Collect Data] --> B[Create defaultdict]
B --> C[Iterate through data]
C --> D[Update defaultdict]
D --> E[Access counted/grouped data]
This diagram illustrates the general workflow of counting grouped elements using defaultdict
in Python.