Sub topic 2
Grouping and Accumulating with `defaultdict`
Assume you know basic dict and list operations, loops, functions, imports, and hashable keys. This chapter uses defaultdict for grouping and accumulation, then introduces deque for queues and stacks.
Grouping with `defaultdict`
defaultdict is a dictionary subclass that creates a value when a missing key is accessed. Its constructor receives a default_factory, a callable that supplies that value.
For grouping, use list as the factory:
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(dict(by_letter))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}The first access to by_letter["a"] creates and stores an empty list. The append then adds the word. This avoids writing a separate membership check.
Use another factory for accumulation:
from collections import defaultdict
totals = defaultdict(int)
for item, amount in [("book", 2), ("pen", 5), ("book", 3)]:
totals[item] += amount
print(dict(totals)) # {'book': 5, 'pen': 5}How `default_factory` Really Works
Indexing a missing key calls the factory and inserts its result:
from collections import defaultdict
scores = defaultdict(int)
scores["new"] += 1
print(scores["new"]) # 1
scores["unused"] # Calls int() and inserts 0
print("unused" in scores) # True
print(scores.get("other")) # None
print("other" in scores) # Falseget() does not call default_factory. Use it when a read must not change the dictionary. A factory must be callable, such as list, set, int, or a function. Passing list() instead of list is an error because it passes one already-created list rather than a factory.
Queues and Stacks with `deque`
deque means double-ended queue. It supports fast insertion and removal at both ends.
from collections import deque
tasks = deque(["write", "test"])
tasks.append("deploy")
tasks.appendleft("plan")
print(tasks.popleft()) # plan
print(tasks.pop()) # deploy
print(tasks) # deque(['write', 'test'])Use append and popleft for a first-in, first-out queue. Use append and pop for a last-in, first-out stack. Unlike a list, a deque is designed for efficient operations at the left end.
Exercise
Which expression reads a missing defaultdict key without inserting it, and which deque operation removes the oldest queued item?
Show answer
Use mapping.get(key) without insertion, and use queue.popleft() for the oldest item.