The Python Collections Module: defaultdict, Counter, and More
The collections module has tools that replace common boilerplate. Here are the ones I use to write shorter, clearer code. The collections module is one of those standard library gems I wish I had learned earlier. It provides specialized container types that replace patterns I used to write by hand. After using it for years, I reach for defaultdict , Counter , and namedtuple almost daily. Here is what each one does and where it shines. defaultdict for Cleaner Grouping A common pattern is grouping items by a key. With a regular dict, you check whether exists, create a list if not, then append. The defaultdict handles the missing-key case automatically by calling a factory function you provide. from collections import defaultdict # Group orders by customer orders_by_customer = defaultdict(list) for order in orders: orders_by_customer[order.customer_id].append(order) Without defaultdict, the same code needs a check on every iteration. The defaultdict version is shorter and expresses the intent clearly: each key maps to a list, initialized empty on first access. I use it for grouping, accumulating counts, and building adjacency lists. The factory can be any callable. defaultdict(int) starts each key at zero,…