← Back to Python, page 3

python-0053 · Medium mid

Explain the defaultdict, Counter, deque and namedtuple tools in collections with a realistic task.

defaultdict creates missing values automatically, Counter counts hashable items and supports arithmetic, deque gives O(1) appends and pops at both ends with an optional maxlen for sliding windows, and namedtuple creates lightweight immutable records with named fields.

Full answer
python
from collections import defaultdict, Counter, deque, namedtuple
Visit = namedtuple("Visit", "user page")
visits = [Visit("asha", "/home"), Visit("ben", "/cart"), Visit("asha", "/cart"), Visit("asha", "/home")]
pages_by_user = defaultdict(set)
for v in visits:
    pages_by_user[v.user].add(v.page)
print({u: sorted(p) for u, p in pages_by_user.items()})
hits = Counter(v.page for v in visits)
print(hits.most_common(1), hits - Counter({"/home": 1}))
recent = deque(maxlen=2)
for v in visits:
    recent.append(v.page)
print(list(recent), visits[0]._replace(page="/about"))

Output:

text
{'asha': ['/cart', '/home'], 'ben': ['/cart']}
[('/home', 2)] Counter({'/cart': 2, '/home': 1})
['/cart', '/home'] Visit(user='asha', page='/about')

defaultdict(set) removes the 'if key not in dict' boilerplate while grouping pages per user. Counter finds the most visited page and subtracts counts, dropping keys that reach zero or below. deque(maxlen=2) keeps only the two most recent pages, discarding older ones automatically, which is a sliding window. The namedtuple gives readable field access and _replace returns a modified copy.

python
from collections import defaultdict, Counter, deque, namedtuple
Visit = namedtuple("Visit", "user page")
visits = [Visit("asha", "/home"), Visit("ben", "/cart"), Visit("asha", "/cart"), Visit("asha", "/home")]
pages_by_user = defaultdict(set)
for v in visits:
    pages_by_user[v.user].add(v.page)
print({u: sorted(p) for u, p in pages_by_user.items()})
hits = Counter(v.page for v in visits)
print(hits.most_common(1), hits - Counter({"/home": 1}))
recent = deque(maxlen=2)
for v in visits:
    recent.append(v.page)
print(list(recent), visits[0]._replace(page="/about"))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • defaultdict for grouping
  • Counter for counting and ranking
  • deque(maxlen) for sliding windows
  • namedtuple for light records

Common mistakes

  • Using list.pop(0) for queues
  • Accidentally creating keys by reading a defaultdict

Follow-ups

  • When would a dataclass replace namedtuple?
  • How does Counter handle negative counts?

Tips

  • Pick a tool per sub-task