Module lessons (3/4)
collections: Counter and defaultdict
Counter for frequency counts, defaultdict for auto-initialized dicts, and namedtuple lightweight records.
What you'll learn in this lesson
- Count frequencies of any iterable in a single line with
Counterand.most_common(). - Eliminate boilerplate
if key not in d:in groupings usingdefaultdict(factory). - Model compact immutable records with
namedtupleand access by field name. - Avoid the silent side effect of accessing a non-existent key in a
defaultdict.
Overview
The built-in containers (list, dict, tuple, set) cover 90% of your needs, but as soon as you have to count occurrences, group elements by key or return lightweight records you find yourself always repeating the same if key not in d:. The collections module encapsulates exactly these recurring patterns in optimized C.
Compare the intent of each container: Counter accumulates frequencies, defaultdict automatically initializes new independent containers at the first key seen, and namedtuple gives readable names to the fields of a tuple without burdening memory.
Sections covered in this lesson
- 11. Instant counting with
Counter - 22. Automatic grouping with
defaultdict - 33. Independent containers vs shared references
- 44. Lightweight and immutable records with
namedtuple - 5Check for understanding
- 6Test yourself
Unlock "collections: Counter and defaultdict" and the full Python Course curriculum
Counter for frequency counts, defaultdict for auto-initialized dicts, and namedtuple lightweight records.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.