collections: smarter containers

Standard Library Tour, lesson 3 of 6

🧰 Standard Library Tour, lesson 3 of 6

collections: smarter containers

Count with Counter, group with defaultdict, queue with deque.

11 min

2 exercises

2 quizzes

0/4 solved

Getting Python ready… examples can run in a moment.

The collections module offers upgraded containers for everyday jobs:

  • Counter: counts things
  • defaultdict: a dict that fills in missing keys
  • deque: a list that's fast at both ends
  • namedtuple: a tuple with named fields
Example

Counter counts for you

A missing key gives 0 instead of a KeyError. Try print(Counter("aab") + Counter("abc")).

Quiz

What does this print?

defaultdict takes a function that makes default values. defaultdict(list) creates an empty list the first time you touch a missing key, which is perfect for grouping. defaultdict(int) starts counts at 0.

Example

Grouping with defaultdict

With a plain dict you'd need an if key not in d: d[key] = [] check first. Try defaultdict(int) with by_letter[w[0]] += 1.

Quiz

What does this print?

deque (say "deck") is a double-ended queue: append, appendleft, pop and popleft are all fast. A list's pop(0) is slow on big lists because every other item has to shift. deque(maxlen=3) keeps only the newest 3 items.

namedtuple creates a lightweight, read-only record type whose fields you access by name or index.

Example

deque: queues and recent history

Adding "maps" pushed "home" out of the history. Try maxlen=2.

Example

namedtuple records

Field names can be a list or one space-separated string. Records are read-only: try top.grade = 100, then top._replace(grade=100) for an updated copy.

Exercise

Top words

Write top_words(text, n) that lowercases the text, splits it into words, counts them with Counter and returns the n most common as a list of (word, count) tuples.

Exercise

Group names by initial

Finish group_by_initial(names) using a defaultdict(list): each key is a name's first letter in uppercase, each value the list of names starting with it (in their original order).