PYTHON

Aggregate Multiple Values per Key using `collections.defaultdict`

Learn to efficiently build dictionaries where each key maps to a list of values, perfect for processing web form data or query parameters with Python's `collections.defaultdict`.

from collections import defaultdict

# Imagine receiving URL query parameters or form data
# where a key might appear multiple times
query_params = [
    ("tag", "python"),
    ("category", "web"),
    ("tag", "django"),
    ("framework", "flask"),
    ("category", "backend")
]

# Use defaultdict(list) to automatically create a list for new keys
aggregated_params = defaultdict(list)

for key, value in query_params:
    aggregated_params[key].append(value)

print(f"Aggregated Parameters: {dict(aggregated_params)}")

# Example: Grouping errors by type
error_logs = [
    ("auth_error", "Invalid credentials"),
    ("db_error", "Connection timed out"),
    ("auth_error", "Token expired"),
    ("network_error", "Host unreachable")
]

errors_by_type = defaultdict(list)
for err_type, message in error_logs:
    errors_by_type[err_type].append(message)

print(f"Errors by Type: {dict(errors_by_type)}")
How it works: This code illustrates `collections.defaultdict`, a dictionary subclass that calls a factory function (like `list` in this case) to supply missing values. It's invaluable for scenarios in web development where you need to aggregate multiple values under a single key, such as parsing URL query strings with repeated parameters, processing multi-select form fields, or categorizing log entries, without needing to check `if key in dict` before appending.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs