python · level 3 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Pick a set or dictionary and a search becomes one step.
A set or dictionary does not search item after item. It works out a , a quick fingerprint of the value, which says exactly where to look. So x in a_set takes about one step, whether it holds ten items or ten million.
The collections module has two dictionaries built for common jobs. A tallies things and ranks them with most_common. A makes an empty list for any new key, so grouping needs no checks.
from collections import Counter, defaultdict
orders = [("Ana", "tea"), ("Ben", "cake"), ("Ana", "scone"), ("Cara", "tea")]
regulars = {"Ana", "Cara"}
print([who for who, item in orders if who in regulars])
print(Counter(item for who, item in orders).most_common(1))
by_person = defaultdict(list)
for who, item in orders:
by_person[who].append(item)
print(dict(by_person)) Sets and dictionaries buy their speed with memory, so keep a list when order and repeats matter.
guess first
Ask a Counter about fish. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
from collections import Counter
votes = Counter(["cats", "dogs", "cats", "cats"])
print(votes["cats"], votes["fish"])
votes["dogs"] = votes["dogs"] + 2
print(votes.most_common())
your turn
Your turn. Find the most used word in a review.
Fill the blank with the tally-keeping dictionary from the import. Then swap in a review of your own if you like.
fix it
Grouping the pets crashes straight away. Fix it!
- The error is a
KeyErrorthe first time a kind appears. Why is the key missing? - A plain dictionary has no list waiting for a new key. The import on line 1 offers one that does.
- Change
by_kind = {}toby_kind = defaultdict(list), then run.
nailed it
you picked the right box for the job. :D
inon a set or dictionary takes about one step.Countertallies things and ranks them withmost_common.defaultdict(list)makes grouping need no checks.
new words in your collection
- hash
- Counter
- defaultdict
This lesson isn’t saved. A free account remembers every lesson you finish.