intermediateLibraries
Collections Module
Specialized container types: Counter, defaultdict, namedtuple, deque.
In this lesson
01Counter & defaultdict
Powerful alternatives to plain dictionaries.
Python
1from collections import Counter, defaultdict23# Counter - count occurrences4words = "the cat sat on the mat the cat".split()5counts = Counter(words)6print(counts.most_common(3))78# defaultdict - auto-create missing keys9groups = defaultdict(list)10for name, score in [("Alice", 90), ("Bob", 85), ("Alice", 95)]:11 groups[name].append(score)12print(dict(groups))
Output
[('the', 3), ('cat', 2), ('sat', 1)]
{'Alice': [90, 95], 'Bob': [85]}02namedtuple & deque
Lightweight data structures for specific use cases.
Python
1from collections import namedtuple, deque23# namedtuple - readable tuple alternative4Point = namedtuple("Point", ["x", "y"])5p = Point(3, 4)6print(f"x={p.x}, y={p.y}")78# deque - fast appends/pops from both ends9d = deque([1, 2, 3])10d.appendleft(0)11d.append(4)12d.rotate(1)13print(list(d))
Output
x=3, y=4 [4, 0, 1, 2, 3]