Summary - Collections
- Python course
- Intermediate
- Lesson 93/116
- 5 min
Combine Counter, defaultdict and deque to write a word frequency counter.
Summary - Collections
In this group we covered Counter, defaultdict, OrderedDict, deque and namedtuple. All five come from the collections module and ease different data tasks.
Counter counts, defaultdict produces defaults for missing keys, OrderedDict keeps and reorders, deque does fast two-ended addition, namedtuple gives immutable tuples with named fields. Now we'll write an example that combines a few of them.
Practice Combined summary example
Start with from collections import Counter, defaultdict. Add the line text = "apple pear apple". Compute word counts with c = Counter(text.split()). Create a defaultdict with d = defaultdict(int) and loop for word in text.split(): with d[word] += 1. Then call print(c["apple"]) and print(d["apple"]).
Starter code
# Count words with Counter and defaultdictSample solution
# Count words with Counter and defaultdict
from collections import Counter, defaultdict
text = "apple pear apple"
c = Counter(text.split())
d = defaultdict(int)
for word in text.split():
d[word] += 1
print(c["apple"])
print(d["apple"])Expected output
2 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool is ideal for counting?
- deque
- Counter Correct answer
- namedtuple
- OrderedDict
Explanation: Counter is designed for counting items.
2 Match the tool and its purpose
| Term | Meaning |
|---|---|
Counter |
Counting |
defaultdict |
Default production |
deque |
Two-ended queue |
namedtuple |
Named tuple |
3 Import Counter and ...
from collections import Counter, ____
text = "apple pear apple"
c = Counter(text.split())
print(c["apple"])
from collections import Counter, defaultdict
text = "apple pear apple"
c = Counter(text.split())
print(c["apple"])
Explanation: defaultdict is also in the collections module.
4 Match the summary example parts
| Term | Meaning |
|---|---|
Counter |
Fast counting |
defaultdict |
Loop counting |
text.split() |
Split words |
d[word] += 1 |
Increment count |