Python 3D Academyবাংলা

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 n
  • defaultdict(list): a dict that makes an empty list the first time a key is used
  • deque: a double-ended queue; append and popleft are both instant
  • namedtuple: a tuple whose items also have names, like p.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:

  1. Counter: counts everything in one go; a missing name counts as 0 instead of raising KeyError, and .most_common(n) gives the top n
  2. defaultdict: a dict that makes a starting value for a new key by itself, so grouping needs no if key not in d check
  3. deque (say "deck"): a queue that is fast at both ends, like a ticket counter line
  4. namedtuple: a tuple whose items have names, so p.x reads better than p[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))
Zara got no votes, so votes["Zara"] is 0, not a KeyError. most_common lists the biggest counts first.
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))
defaultdict(list) calls list() to make an empty list the first time a new letter appears. defaultdict(int) would start each key at 0.

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))
With maxlen=3, adding "weather" pushed "home" out of the front. p._replace(x=10) is a new Point; p itself is unchanged.

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) after append(3) is deque([2, 3], maxlen=2).
  • Expecting Counter to fail on a missing key. c["z"] is 0, which can hide a typo.

Quiz

  1. What does this print?

    from collections import Counter
    
    c = Counter("banana")
    print(c["a"], c["z"])
  2. What does this print?

    from collections import Counter
    
    print(Counter(["tea", "coffee", "tea"]).most_common(1))
  3. 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))
  4. What does this print?

    from collections import deque
    
    q = deque(["Mina", "Rafi"])
    q.append("Tara")
    print(q.popleft(), list(q))
  5. 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

  1. Write top_letter(word: str) -> str with Counter: the letter that appears most. If two letters tie, give back the one that appears first in the word.

  2. Write group_by_length(words: list[str]) -> dict[int, list[str]] with defaultdict: words grouped by how many letters they have, in the order they come. Give back a plain dict.

  3. Write recent(pages: list[str], n: int) -> list[str] with deque(maxlen=n): the last n pages visited, oldest first. With n of 0 it gives back an empty list.