PYTHON
Grouping Data Efficiently with defaultdict
Learn how to efficiently group items by a common key in Python using collections.defaultdict, perfect for organizing data in web applications.
from collections import defaultdict
# Example data: a list of dictionaries (e.g., blog posts)
posts = [
{"id": 1, "title": "First Post", "author": "Alice"},
{"id": 2, "title": "Second Post", "author": "Bob"},
{"id": 3, "title": "Third Post", "author": "Alice"},
{"id": 4, "title": "Fourth Post", "author": "Charlie"},
{"id": 5, "title": "Fifth Post", "author": "Bob"},
]
# Group posts by author
posts_by_author = defaultdict(list)
for post in posts:
posts_by_author[post["author"]].append(post)
# Print the grouped data
for author, author_posts in posts_by_author.items():
print(f"Author: {author}")
for post in author_posts:
print(f" - {post['title']} (ID: {post['id']})")
# Accessing posts by a specific author
print("
Alice's posts:")
for post in posts_by_author["Alice"]:
print(f" - {post['title']}")
How it works: This snippet demonstrates using collections.defaultdict(list) to group a list of dictionaries (e.g., blog posts) by a common key (e.g., author). When an author key is accessed for the first time, defaultdict automatically initializes its value as an empty list, allowing you to directly append new posts without checking if the key already exists. This simplifies code and makes data aggregation more efficient and readable for web applications.