Course outline · 0% complete

0/27 lessons0%

Course overview →

collections: Counter, defaultdict, deque

lesson 6-1 · ~14 min · 15/27

Quiz

Warm-up from lesson 2-3: sorted(d.items(), key=lambda kv: kv[1]) sorts a dict's pairs by what?

Counter: counting without boilerplate

The standard library exists so you do not rewrite, and re-debug, the same chores in every project. Counting things and grouping things are the two most common data chores in working Python, and this unit's collections module turns each into a line or two.

Counting things in Python for Beginners took four lines: check if the key exists, initialize it, increment. collections.Counter does it in one:

from collections import Counter

votes = ["cat", "dog", "cat", "bird", "cat"]
tally = Counter(votes)
# Counter({'cat': 3, 'dog': 1, 'bird': 1})

A Counter is a dict (it subclasses dict, inheritance from lesson 3-4 in the wild), with extras:

  • tally.most_common(2) gives the top two (item, count) pairs.
  • Missing keys return 0 instead of raising KeyError.
  • Feed it any iterable: a list, a string, a generator from unit 4.

Code exercise · python

Run this program. One line to count, one method to rank.

Code exercise · python

Your turn. Count the votes with Counter, then use most_common(1) to get the winner. most_common returns a LIST of (item, count) pairs, so take element [0] and unpack it into two variables. Print the winner's name and vote count.

defaultdict and deque

defaultdict is a dict that invents a default value for missing keys. Pass it the factory to use, like list or int:

from collections import defaultdict

groups = defaultdict(list)
groups["fruit"].append("apple")   # no KeyError, a fresh [] appears

That kills the if key not in d: d[key] = [] dance forever, and it is the standard tool for grouping.

deque (say "deck", short for double-ended queue) stores its items so that both ends are directly reachable. As a result, appendleft and popleft take the same tiny, fixed amount of time no matter how many items the deque holds. A plain list cannot offer that: list.pop(0) must shift every remaining element one slot left, so its cost grows with the length of the list. Use a deque whenever you need a queue, like breadth-first search in the Data Structures course. (Unit 9 turns this kind of cost reasoning into a formal habit.)

Code exercise · python

Your turn. Group the words by their first letter using a defaultdict(list). Print the dict converted with dict(...) so it displays plainly.

Quiz

Why prefer deque over list for a queue where you remove from the front?