collections: Counter, defaultdict, deque and namedtuple
🌍 In real life. After a class election, someone reads out each vote while someone else makes tally marks next to each name. You did exactly that in Chapter 11 with counts.get(x, 0) + 1. Here is that tally again:
The idea in one sentence: the collections module has ready-made containers for everyday jobs: Counter counts, defaultdict fills in missing keys, deque adds and removes fast at both ends, and namedtuple names a tuple's fields.
Its words:
Counter(items): counts; a missing item counts as 0;.most_common(n)gives the top ndefaultdict(list): a dict that makes an empty list the first time a key is useddeque: a double-ended queue;appendandpopleftare both instantnamedtuple: a tuple whose items also have names, likep.x
Counting is needed so often that Python ships a ready-made tool for it. The collections module has four you'll use again and again. Step by step:
Counter: counts everything in one go; a missing name counts as 0 instead of raisingKeyError, and.most_common(n)gives the top ndefaultdict: a dict that makes a starting value for a new key by itself, so grouping needs noif key not in dcheckdeque(say "deck"): a queue that is fast at both ends, like a ticket counter linenamedtuple: a tuple whose items have names, sop.xreads better thanp[0]
from collections import Counter
votes = Counter(["Mina", "Rafi", "Mina", "Tara", "Mina", "Rafi"])
print(votes)
print(votes["Mina"], votes["Zara"])
print(votes.most_common(1))
letters = Counter("banana")
print(letters.most_common(2))from collections import defaultdict
by_letter = defaultdict(list)
for name in ["Mina", "Rafi", "Mitu", "Tara", "Rana"]:
by_letter[name[0]].append(name)
print(dict(by_letter))A line at the ticket counter. People join at the back and are served from the front. With a plain list, pop(0) makes Python shuffle every other item forward, which gets slow for long lines. A deque is built for this: append adds at the back, popleft takes from the front, both instantly.
Give it maxlen and it keeps only the newest items, like a phone's "recent calls" list. And namedtuple makes a small record type in one line: its items have names, and like any tuple it can't be changed (use _replace to make a changed copy).
from collections import deque, namedtuple
line = deque(["Mina", "Rafi"])
line.append("Tara")
print("serving", line.popleft())
print(list(line))
recent = deque(maxlen=3)
for page in ["home", "news", "sport", "weather"]:
recent.append(page)
print(list(recent))
Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p, p.x + p.y)
print(p._replace(x=10))Why use them? Each one replaces a few lines you'd otherwise write again and again (the get(x, 0) + 1 tally, the "if the key isn't there, make a list" check), with code that's already tested and often faster. deque.popleft() is instant where list.pop(0) moves every other item.
Mistakes and edge cases.
- defaultdict(list()) with brackets passes an empty list instead of the maker; write
defaultdict(list). - Looking up creates keys. Just reading
d["x"]on a defaultdict adds"x"with an empty value. - A deque with maxlen. When it's full, adding at one end silently drops an item from the other:
deque([1, 2], maxlen=2)afterappend(3)isdeque([2, 3], maxlen=2). - Expecting Counter to fail on a missing key.
c["z"]is 0, which can hide a typo.
Quiz
What does this print?
from collections import Counter c = Counter("banana") print(c["a"], c["z"])What does this print?
from collections import Counter print(Counter(["tea", "coffee", "tea"]).most_common(1))What does this print?
from collections import defaultdict groups = defaultdict(list) for word in ["apple", "avocado", "banana"]: groups[word[0]].append(word) print(dict(groups))What does this print?
from collections import deque q = deque(["Mina", "Rafi"]) q.append("Tara") print(q.popleft(), list(q))Which line has a mistake?
from collections import namedtuple Point = namedtuple("Point", "x y") p = Point(1, 2) p.x = 5 print(p)
Coding tasks
Write
top_letter(word: str) -> strwithCounter: the letter that appears most. If two letters tie, give back the one that appears first in the word.Write
group_by_length(words: list[str]) -> dict[int, list[str]]withdefaultdict: words grouped by how many letters they have, in the order they come. Give back a plaindict.Write
recent(pages: list[str], n: int) -> list[str]withdeque(maxlen=n): the lastnpages visited, oldest first. Withnof 0 it gives back an empty list.