Use the collections module's ready-made tools: Counter for counting, defaultdict for grouping without KeyError, deque for fast queues, and namedtuple for readable records.
Module 4, lesson 4
About 8 minutes
Builds on earlier lessons
12-question quiz at the end
What you will learn
Count with Counter
Group with defaultdict
Queue with deque
Name with namedtuple
Ready-made tools in collections
Python's collections module comes with four handy tools. Import one and skip writing it yourself.
Borrowing a tool
One line brings a tool into your program. Tap each part to see its job.
Try each tool
Pick an example, change it, then press Run. Say what you expect to see before you press.
Watch a vote get counted
Press Step to run one line at a time. A class votes for its favourite pet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Common collections misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Notes
Everything above, in words. Open it when you want the full explanation.
Syntax
The general shape of the statements in this lesson.
Worked examples
Read the problem, run the code, then read why it works.
Common pitfalls
Mistakes people make with this topic, and what to write instead.
In the real world
Where this shows up in software people use every day.
Key takeaways
Common questions
Guess the answer first, then open it.
Your notes
Sign in to keep private notes alongside this lesson.
The standard library is the large set of modules that comes with every Python installation. A module is a file of ready-made code, and import makes its contents available. The collections module provides extra collection types built on top of the dictionaries, lists and tuples you already know.
Three things make it better than the hand-written pattern. A missing item gives 0 instead of KeyError. most_common(n) returns the top n items as (item, count) pairs, from most to least common. And you can keep counting: tally.update(["tea"]) adds more items, and tally["tea"] += 1 works too.
Counter works on strings, so Counter("banana") counts letters. Two counters can be added together with + to combine tallies from different days.
defaultdict: no more missing keys
A defaultdict is a dictionary that creates a starting value the first time a missing key is used. You tell it which kind of value to create by passing a type such as int, list or set.
Try it 3: edit me, then Run
1
2
3
4
5
6
7
8
9
10
11from collections import defaultdict
words = ["apple", "avocado", "banana", "cherry", "blueberry"]
by_letter =defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(by_letter["b"]) # ['banana', 'blueberry']
minutes =defaultdict(int)
for day, mins in [("Mon", 20), ("Tue", 15), ("Mon", 30)]:
minutes[day] += mins
print(minutes["Mon"]) # 50
Output
Press Run to see what it prints.
defaultdict(list) gives a new empty list for each new key, so you can append straight away. defaultdict(int) starts each new key at 0, ready for +=. This replaces both setdefault() and get(key, 0) from the dictionaries lesson.
Be aware that even reading a missing key adds it with the default value. Use key in d when you only want to check, so you do not fill the dictionary with empty entries by accident.
deque: a fast queue
A deque (say "deck") is a list-like sequence that is fast to add to and remove from at both ends. A normal list is fast at the end but slow at the front, because removing the first item shifts every other item along. For queues, where the first to arrive is the first served, a deque is the right tool.
Try it 4: edit me, then Run
1
2
3
4
5
6from collections import deque
queue =deque(["Ana", "Bo"])
queue.append("Cy") # join at the back
queue.appendleft("VIP") # jump to the front
first = queue.popleft() # serve the frontprint(first, list(queue)) # VIP ['Ana', 'Bo', 'Cy']
Output
Press Run to see what it prints.
deque(maxlen=3) keeps only the newest three items; adding a fourth drops the oldest automatically, which is perfect for "the last few readings" or a recent history list. rotate(1) moves the last item to the front.
namedtuple: tuples with names
A plain tuple such as (3, 4) gives no hint what each part means. namedtuple creates a small new type whose fields have names, so code says point.x instead of point[0].
Try it 5: edit me, then Run
1
2
3
4
5
6from collections import namedtuple
Point =namedtuple("Point", ["x", "y"])
p =Point(3, 4)
print(p.x + p.y) # 7print(p) # Point(x=3, y=4)
x, y = p # still unpacks like a tuple
Output
Press Run to see what it prints.
A named tuple is still a tuple: it is immutable, it unpacks, and it works anywhere a tuple does. It prints with its field names, which makes debugging easier. The first argument is the type's name and is conventionally the same as the variable, written with a capital letter. To change a field, p._replace(x=10) returns a new tuple.
Which tool when?
Counting things: Counter.
Grouping or totalling under keys: defaultdict(list) or defaultdict(int).
First in, first out, or keeping only the last few items: deque.
A small fixed record with named parts: namedtuple.
None of these do anything you could not write yourself with plain dictionaries, lists and tuples, and the plain versions are always fine. The collections versions are shorter, faster to read and well tested, which is why experienced programmers reach for them.
Two ways to import
You can also write import collections and then use the full name, as in collections.Counter(votes). The longer form makes it obvious where each name comes from, which helps in big programs; the from ... import form is shorter and reads well when you use a few names often. Both are correct. What you should avoid is naming your own file collections.py, because Python would then import your file instead of the real module, and every name you try to use from it would be missing.
Learning more of the library
The standard library has hundreds of modules. You do not need to learn them all; you need to know they exist and how to look one up. The official documentation for each module starts with a short summary and examples, and help(Counter) in the editor prints the same information.
syntax.py
1
2
3
4
5
6from collections import Counter, defaultdict, deque, namedtuple
c =Counter(items) c["x"] c.most_common(3) c.update(more)
d =defaultdict(list) d[k].append(v)
t =defaultdict(int) t[k] +=1
q =deque() q.append(x) q.appendleft(x) q.popleft() deque(maxlen=5)
Point =namedtuple("Point", ["x", "y"]) p =Point(1, 2) p.x
Output
Press Run to see what it prints.
Example 1 of 2
Top words in a review
Beginner
Find the three most common words in a short review, ignoring case and punctuation.
Python
1
2
3
4
5
6from collections import Counter
review ="Good food, good price. Friendly staff and good coffee. Coffee was hot."
cleaned = review.lower().replace(",", "").replace(".", "")
counts =Counter(cleaned.split())
for word, count in counts.most_common(3):
print(word, count)
Output
Press Run to see what it prints.
Predict first
How it works(open after your guess)
The text is cleaned so that Coffee and coffee, and coffee. with its full stop, count as the same word. Counter does the counting in one line, and most_common(3) returns the top three pairs. When counts tie, items keep the order in which they first appeared, which is why food comes before price.
A help desk queue
Beginner
Model a help desk where customers join a queue, one urgent customer goes to the front, and two customers are served in order.
Python
1
2
3
4
5
6
7
8from collections import deque
queue =deque()
for name in ["Ana", "Bo", "Cy"]:
queue.append(name)
queue.appendleft("Urgent")
for _ inrange(2):
print("Serving", queue.popleft())
print("Waiting:", list(queue))
Output
Press Run to see what it prints.
Predict first
How it works(open after your guess)
append() adds to the back and popleft() takes from the front, so customers are served in the order they arrived, except the urgent one placed at the front with appendleft(). A list would need pop(0), which gets slower as the queue grows.
Pitfall 1 of 3
Forgetting the import
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
Buggy code: run it
1tally =Counter(["a", "b"])
Output
Press Run to see what it prints.
Show what goes wrong and the fixWhat goes wrong and the fix
What happens
NameError: name 'Counter' is not defined
Write this instead
from collections import Counter
tally =Counter(["a", "b"])
Why it happens
Counter lives in the collections module and is not available until you import it.
Calling the default instead of passing it
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
Buggy code: run it
1
2from collections import defaultdict
groups =defaultdict(list())
Output
Press Run to see what it prints.
Show what goes wrong and the fixWhat goes wrong and the fix
What happens
TypeError: first argument must be callable or None
Write this instead
from collections import defaultdict
groups =defaultdict(list)
Why it happens
list() makes one empty list. defaultdict needs the type itself, list, so it can make a new list for every key.
Reading a defaultdict adds keys
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
Show what goes wrong and the fixWhat goes wrong and the fix
What happens
Prints 1; reading Zed created the key
Write this instead
from collections import defaultdict
scores =defaultdict(int)
if"Zed"in scores and scores["Zed"] >0:
print("Zed scored")
print(len(scores))
Why it happens
Any lookup of a missing key creates it with the default value, even inside an if.
A library returns desk
Libraries
A library groups returned books by genre for re-shelving and keeps a short history of the last three returns for the desk screen.
Why Python fits
Named fields make book.genre self-explanatory, defaultdict(list) groups without any key checks, and a deque with maxlen=3 drops the oldest title automatically.
Python
1
2
3
4
5
6
7
8
9
10
11from collections import defaultdict, deque, namedtuple
Book =namedtuple("Book", ["title", "genre"])
returns = [Book("Holes", "fiction"), Book("Atlas", "reference"), Book("Wonder", "fiction"), Book("Cosmos", "science")]
shelves =defaultdict(list)
recent =deque(maxlen=3)
for book in returns:
shelves[book.genre].append(book.title)
recent.append(book.title)
for genre insorted(shelves):
print(genre, shelves[genre])
print("Recent:", list(recent))
Output
Press Run to see what it prints.
Tick each one you could explain to a friend.
0 of 5
Is a Counter a dictionary?
Yes, it is a special kind of dictionary, so items(), keys() and looping all work as usual.
Should I always use defaultdict instead of dict?
No. Use a plain dictionary when a missing key should be an error. defaultdict suits counting and grouping, where missing keys are expected.
Can I sort a Counter?
most_common() with no argument returns every item sorted by count. sorted(counter) sorts the keys alphabetically.