Legends ofPythos
Claim your name
Pythonic Python

The collections module

Lesson 8 of 12

Watch the lesson1:17 · with Sigrid
Python's standard library includes a package called collections. It holds data structures that solve common problems more cleanly than raw dictionaries or lists. Today you will meet three: Counter, defaultdict, and namedtuple.

Counter

Counting how often each item appears in a list usually takes four lines of manual dictionary work. collections.Counter does it in one.
from collections import Counter

colors = ['red', 'blue', 'red', 'green', 'blue', 'red']
result = Counter(colors)
print(result)
Counter acts like a dict, but it counts for you.
Counter is also handy when merging two Counters: simply add them together with + (plain dictionaries can't be added). It returns the most common elements via .most_common(n) as well.

defaultdict

A normal dictionary raises KeyError when you read a key that is not there. A defaultdict lets you supply a factory so missing keys are created automatically.
from collections import defaultdict

groups = defaultdict(list)
for name in ['Alice', 'Bob', 'Carol']:
    groups[name[0].lower()].append(name)
No need to check if a key exists before appending.
defaultdict(int) is especially common for accumulating totals, because int() returns 0. You can also use any zero-argument callable as the factory.

namedtuple

A plain tuple like (1, 'Alice') is fine for data, but you cannot tell which position means what. A namedtuple gives fields names while keeping the lightweight, immutable nature of a regular tuple.
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 7)
print(p.x + p.y)
Reads like a record with named fields.
namedtuple supports unpacking and indexing just like tuples: p[0], x, y = p. It is also hashable, so you can use instances as dictionary keys or set members. For mutable records with defaults and methods, reach for a dataclass instead.

Your turn

0 of 3 solved

Exercise 1

+35 XP
Define a variable called drink_orders that counts how many times each beverage in the provided list beverages appears. Use collections.Counter.
beverages = ['latte', 'mocha', 'espresso', 'mocha', 'cappuccino']
drink_orders = None

Run your code to check it against the tests.

Exercise 2

+35 XP
Build a dictionary called letters that groups each name in the provided names list under its first letter (lowercased). Each value should be a list of full names. Use collections.defaultdict(list) so you never need to check whether a key already exists.
names = ['Alice', 'Bob', 'Ava', 'Ben']
letters = None

Run your code to check it against the tests.

Exercise 3

+35 XP
Create a namedtuple type called Rect whose fields are width and height. Then build an instance rect with width 4 and height 6, and store the sum of its two dimensions in area_sum.
Rect = None
rect = None
area_sum = None

Run your code to check it against the tests.