Practical applications of defaultdict
Counting Occurrences
One of the most common use cases for defaultdict
is counting the occurrences of elements in a list or any other iterable. Here's an example:
from collections import defaultdict
## Count the occurrences of elements in a list
fruits = ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'cherry']
fruit_count = defaultdict(int)
for fruit in fruits:
fruit_count[fruit] += 1
print(fruit_count)
## Output: defaultdict(<class 'int'>, {'apple': 2, 'banana': 2, 'cherry': 3})
In this example, we use a defaultdict
with a default value of int
to count the occurrences of each fruit in the fruits
list.
Grouping Data
Another common use case for defaultdict
is grouping data based on a certain key, where the number of groups is not known in advance. Here's an example:
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(grade_groups)
## Output: defaultdict(<class 'list'>, {'A': ['Alice', 'Charlie'], 'B': ['Bob', 'Eve'], 'C': ['David']})
In this example, we use a defaultdict
with a default value of list
to group the students by their grades. The keys in the grade_groups
dictionary are the unique grades, and the values are lists of student names for each grade.
Nested Dictionaries
defaultdict
is also useful when working with nested dictionaries, as it can help you avoid KeyError
exceptions when accessing nested keys. Here's an example:
from collections import defaultdict
## Create a nested dictionary using defaultdict
person_data = defaultdict(lambda: defaultdict(str))
person_data['Alice']['age'] = 25
person_data['Alice']['city'] = 'New York'
person_data['Bob']['age'] = 30
person_data['Bob']['city'] = 'Los Angeles'
print(person_data)
## Output: defaultdict(<function <lambda> at 0x7f6a8c0c8820>, {'Alice': {'age': 25, 'city': 'New York'}, 'Bob': {'age': 30, 'city': 'Los Angeles'}})
In this example, we create a nested defaultdict
where the outer dictionary has a default value of another defaultdict
with a default value of an empty string. This allows us to easily add new keys and values to the nested dictionary without having to check if the intermediate keys exist.
graph TD
A[Counting Occurrences] --> B[Grouping Data]
B --> C[Nested Dictionaries]
C --> D[Other Applications]
These are just a few examples of the practical applications of defaultdict
in Python. The versatility of this data structure makes it a valuable tool in a wide range of programming scenarios.