11. Collections Gems
The collections module contains several standard-library data structures that solve common problems cleanly. Three especially useful ones are Counter, defaultdict, and deque.
11.1. Counter
Counter is useful when you want to count how often values appear.
1from collections import Counter
2
3
4words = ['red', 'blue', 'red', 'green', 'blue', 'red']
5counts = Counter(words)
6
7print(counts)
8print(counts['red'])
9print(counts.most_common(2))
11.2. defaultdict
defaultdict helps when missing keys should automatically start with a sensible default value.
1from collections import defaultdict
2
3
4grouped = defaultdict(list)
5
6pairs = [('fruit', 'apple'), ('fruit', 'pear'), ('drink', 'water')]
7for category, item in pairs:
8 grouped[category].append(item)
9
10print(grouped)
With a normal dictionary, you would need to check whether the key exists before appending to the list.
11.3. deque
deque is a double-ended queue. It is a better fit than a list when you need to add or remove items efficiently from both ends.
1from collections import deque
2
3
4tasks = deque(['wash dishes', 'write report'])
5tasks.append('call mom')
6tasks.appendleft('drink coffee')
7
8print(tasks.popleft())
9print(tasks.pop())
10print(tasks)
11.4. Why these matter
These types are worth learning early because they express intent directly. Counter means frequency counting, defaultdict means default values on first access, and deque means queue-like behavior. Using the right data structure usually makes the code shorter and easier to understand.
11.5. Exercise
Build a tiny checkout analytics script for a coffee shop. You are given a list of drink orders, where each order is a tuple of (customer_name, drink_name). Use:
Counterto find the three most common drinksdefaultdict(list)to group drinks by customerdequeto model a line of waiting orders and process them from the left
1orders = [
2 ('Ava', 'latte'),
3 ('Noah', 'tea'),
4 ('Ava', 'espresso'),
5 ('Mia', 'latte'),
6 ('Noah', 'latte'),
7 ('Luca', 'tea'),
8 ('Ava', 'latte'),
9]