Dictionaries and Sets · Lesson 21 of 39
Choosing the Right Collection
You now know four built-in collections. Choosing the right one makes code shorter, faster and easier to read – and "why did you use a set here?" is a question interviewers love. This lesson gives you a quick way to decide, then introduces three power tools from the collections module.
In this lesson
- A decision diagram and comparison table
Counterfor countingdefaultdictfor groupingdequefor queues
Which collection?
Ask what you need to do with the data
What is the main job?
- Look up values by a name or ID→
dict - Keep only unique items / fast "is it there?"→
set - Ordered items that change→
list - A fixed record or a dict key→
tuple
| list | tuple | dict | set | |
|---|---|---|---|---|
| Syntax | [1, 2] | (1, 2) | {"a": 1} | {1, 2} |
| Ordered | yes | yes | yes (insertion) | no |
| Mutable | yes | no | yes | yes |
| Duplicates | allowed | allowed | unique keys | no |
| Access by | index | index | key | – (membership only) |
x in c speed | slow (scan) | slow (scan) | fast (hash) | fast (hash) |
Counter: counting made easy
Remember the word-counting loop from the Dictionaries lesson? Counter replaces it:
from collections import Counter
votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"]
tally = Counter(votes)
print(tally)
print(tally["tea"], tally["water"]) # missing items count as 0
print(tally.most_common(2))
letters = Counter("mississippi")
print(letters.most_common(1))
Counter({'tea': 3, 'coffee': 2, 'juice': 1})
3 0
[('tea', 3), ('coffee', 2)]
[('i', 4)]Counters can even be added and compared, which makes anagram checks a one-liner:
from collections import Counter
print(Counter("listen") == Counter("silent"))
True
defaultdict: no more "if key not in"
A defaultdict creates a default value the first time you touch a missing key. Grouping becomes trivial:
from collections import defaultdict
orders = [("Asha", 250), ("Ben", 120), ("Asha", 90), ("Chen", 300), ("Ben", 60)]
spent = defaultdict(int) # missing keys start at 0
history = defaultdict(list) # missing keys start as []
for customer, amount in orders:
spent[customer] += amount
history[customer].append(amount)
print(dict(spent))
print(dict(history))
{'Asha': 340, 'Ben': 180, 'Chen': 300}
{'Asha': [250, 90], 'Ben': [120, 60], 'Chen': [300]}deque: a fast queue
Removing from the front of a list (pop(0)) is slow because every other item shifts left. A deque ("deck", double-ended queue) adds and removes at both ends instantly:
from collections import deque
queue = deque(["order-1", "order-2"])
queue.append("order-3") # join at the back
first = queue.popleft() # serve from the front
print(first, list(queue))
recent = deque(maxlen=3) # keeps only the last 3
for page in ["home", "blog", "python", "quiz", "about"]:
recent.append(page)
print(list(recent))
order-1 ['order-2', 'order-3'] ['python', 'quiz', 'about']
Queue (first in, first out)
- append()new items join at the back
- dequeorder-2, order-3 waiting
- popleft()the oldest item is served first
For a stack (last in, first out – like the Undo button) a plain list is perfect: append() to push and pop() to take the top.
Putting it together
Which product categories sold, and how many unique customers bought from each?
from collections import defaultdict
sales = [
("Asha", "books"), ("Ben", "toys"), ("Asha", "books"),
("Chen", "books"), ("Ben", "games"), ("Dia", "toys"),
]
buyers = defaultdict(set)
for customer, category in sales:
buyers[category].add(customer)
for category, people in sorted(buyers.items()):
print(f"{category}: {len(people)} customers {sorted(people)}")
books: 2 customers ['Asha', 'Chen'] games: 1 customers ['Ben'] toys: 2 customers ['Ben', 'Dia']
A dict to group, a set to keep customers unique – each collection doing what it is best at.
Practice
Try it yourself
Which collection would you use for: (a) a user's browser history, (b) the list of countries a site supports, for fast checking, (c) a phone book, (d) an (x, y) point?
Show solution
(a) a list (or
deque(maxlen=…)), (b) a set, (c) a dict, (d) a tuple.Find the three most common words in "a b c a b a d e a b".
Show solution
from collections import Counter print(Counter("a b c a b a d e a b".split()).most_common(3))[('a', 4), ('b', 3), ('c', 1)]
Quick check
What does Counter("aab")["z"] return?
0 – a Counter returns 0 for missing items instead of raising KeyError.
Why use deque instead of a list for a queue?
popleft() on a deque is instant, while list.pop(0) shifts every remaining item.
What does defaultdict(list) give for a new key?
An empty list, created automatically.
Summary
- dict for lookups, set for uniqueness and fast membership, list for ordered changing data, tuple for fixed records.
Countercounts,defaultdictgroups,dequeis a fast queue.
Practise in interview format: Python data structures and collections module set.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.