Legends ofPythos
Claim your name
Pythonic Python

The collections module

Lesson 8 of 12

Watch the lesson5:50 · with Sigrid
Python comes with a module called collections. It holds ready-made tools for storing data, which do some common jobs more neatly than plain dictionaries or lists. In this lesson you'll meet three: Counter, defaultdict and namedtuple. Import each one from collections before you use it, for example from collections import Counter.

Counter

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

votes = ['cat', 'dog', 'cat', 'owl']
result = Counter(votes)
print(result)
A Counter works like a dictionary, but it counts for you.
You can add two Counters together with +, which adds up their counts (plain dictionaries can't be added). And .most_common(n) gives the n most common items, each with its count: here, result.most_common(1) gives [('cat', 2)].

defaultdict

A normal dictionary raises KeyError when you read a key that is not there. A defaultdict fills in a missing key for you. You tell it how to make the starting value: defaultdict(list) gives each new key an empty list.
from collections import defaultdict

groups = defaultdict(list)
for name in ['Alice', 'Bob', 'Carol']:
    groups[name[0].lower()].append(name)
print(dict(groups))
No need to check if a key exists before appending.
The example above prints {'a': ['Alice'], 'b': ['Bob'], 'c': ['Carol']}. Printed as it is, a defaultdict shows some extra words, so dict() turns it into a plain dictionary first.

defaultdict(int) is common for adding up totals, because int() gives 0. Notice there are no brackets after list or int: you hand over the function itself, and the defaultdict calls it each time it needs a starting value. Any function you can call with nothing in its brackets will do.

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.
A named tuple is still a tuple, so p[0] and x, y = p work too. Like any tuple, it can't be changed once it's made. So, if what it holds can't be changed either, it can be a dictionary key, or go in a set. If you need a record you can change, with default values and methods, use 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 drink in the list beverages appears. Use collections.Counter: put from collections import Counter at the top of your code, then write Counter on its own.
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 list names under its first letter, in lower case. Each value should be a list of full names. Use defaultdict(list) so you never need to check whether a key already exists, and put from collections import defaultdict at the top of your code.
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 its width plus its height (added, not multiplied) in area_sum. Put from collections import namedtuple at the top of your code.
Rect = None
rect = None
area_sum = None

Run your code to check it against the tests.