Lesson 4 of 10
Counting with Counter
- 10 min
- 5 checks
- 3 hints
- Go to task
Goal
How many times each item appears
Explanation
"How many times does each item appear?" comes up with every kind of data, like the words in a review or the products in a list of orders. If you write the loop yourself, you have to check on every pass whether the key exists before you can bump its count.
Counter from collections does it in one line: Counter(orders) returns a dict whose keys are the items and whose values are how many times each one appears. .most_common(2) returns the two most frequent items, from most to least, each as a pair of the item and its count. And if you ask about an item that isn't there, you get 0 instead of a KeyError.
Watch out: a string is itself a sequence of characters, so Counter("great great") counts the letters and the space, not the words. Split the text into words first with .split().
Your task
Build counts from orders using Counter, and put the two most-ordered products in top using most_common. Then build word_counts from the sentence review, holding how many times each word appears.
Checks
5 checks- counts counts every product
- counts is a Counter
- top holds the two most-ordered products
- top is computed with most_common
- word_counts counts words, not letters