collections
coreintermediatecollections supplies specialized containers — Counter, defaultdict, namedtuple, deque — that replace common hand-written patterns built from plain dicts and lists.
Think of it as
A plain dict or list is a blank container you configure by hand every time. collections is a drawer of pre-built containers, each one solving exactly one recurring problem: counting, auto-initializing, naming fields, or fast ends.
What we're doing: Use Counter to tally word frequency and defaultdict to group results, the two most common collections patterns.
- 5
- Counter(words) tallies each string in one pass — no manual dict.get(word, 0) + 1 loop needed.
- 6
- .most_common(2) returns the two highest counts as (item, count) tuples, already sorted.
- 9
- length_groups[len(word)] never raises KeyError on a new length — defaultdict(list) creates [] automatically.
[('the', 3), ('fox', 2)]
{3: ['the', 'the', 'the', 'fox', 'fox', 'dog'], 5: ['quick'], 4: ['lazy']}Why this works: Counter and defaultdict both remove a manual "check if the key exists first" step. Counter treats every item as a key to tally; defaultdict runs its factory function exactly when a key is missing, so the append on line 10 always has a list to append to.
Using a plain dict and manually checking for a missing key
Wrong
Better
What you see: Not a crash — working code, but four lines of boilerplate repeated at every call site that groups items into a dict of lists.
Why: defaultdict(list) moves the "is this key new?" check into the container itself, so every call site that groups data reads the same one line instead of reimplementing the check-then-initialize pattern.
- Counting items — Counter
- Grouping into a dict — defaultdict(list)
- Named fields — namedtuple
- Fast both ends — deque
collections — the containers worth knowing
Together
Remember: Counter tallies, defaultdict auto-creates missing values, namedtuple names fields, deque is fast at both ends — pick the one matching the shape of the problem.
See also: collections abc and typing · dictionaries · dataclass basics

