Group event labels with defaultdict

Group event labels with defaultdict

Author: Batu. AI assistance was used to draft this article.

When one event identifier can carry several labels, collections.defaultdict(list) removes the branch normally needed to initialize each group. Its default_factory is list, so the first labels_by_event[event_id] access creates a new empty list for that key. Calling .append(label) then records the label; later rows with the same identifier append to that same list. The resulting dictionary preserves the labels for evt-101 in input order: cache-miss, then retry.

The first assertion compares a regular dict view with the intended groups. The second assertion is deliberately placed before reading an absent event. Accessing labels_by_event["evt-999"] produces [] and inserts evt-999, which the third assertion confirms. This side effect matters when a lookup should not alter stored groups.

For a non-mutating absence check, use labels_by_event.get(event_id) or test membership with event_id in labels_by_event; neither invokes the default factory. This grouping recipe requires a callable factory such as list. More generally, defaultdict permits default_factory=None; then a missing __getitem__ lookup raises KeyError. Event IDs must be hashable keys. The recipe does not remove duplicates: repeated input rows remain repeated in the list. If labels must be unique, use defaultdict(set) and explicitly order values when presentation order matters. defaultdict is available in Python 2.5 and later.

Source: Python defaultdict documentation.

from collections import defaultdict

events = [
    ("evt-101", "cache-miss"),
    ("evt-102", "validated"),
    ("evt-101", "retry"),
]
labels_by_event = defaultdict(list)

for event_id, label in events:
    labels_by_event[event_id].append(label)

assert dict(labels_by_event) == {
    "evt-101": ["cache-miss", "retry"],
    "evt-102": ["validated"],
}
assert "evt-999" not in labels_by_event

print("evt-101:", ",".join(labels_by_event["evt-101"]))
print("missing:", labels_by_event["evt-999"])
assert "evt-999" in labels_by_event

Expected stdout

evt-101: cache-miss,retry
missing: []

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic