──────────────────────────────────────

19. Repair Desk Intake · Count and Rank Repair Categories

Build a tally with Counter and rank the most frequent categories.

Lesson files · lessons/iterators-and-toolkit/count-and-rank-categories

Before you start
- Read a value from a dictionary by key.
- Unpack a pair into two names in a for loop.

By the end
- Use Counter to count requests and look up a category with no entries.
- Use most_common() to report the two busiest categories.
- Explain the order of tied categories using the original input.

Where you can use it
A repair desk coordinator can send more volunteers to the busiest benches and check whether any battery work came in.

Counter is a type of dictionary from the collections module. Give it an iterable and it counts each value it receives. To add another batch, call counts.update(new_items). Looking up a missing key with counts["battery"] gives 0. The total() method adds all the counts.

The most_common(2) method returns up to two pairs of category and count, highest count first. Ties keep the order in which those categories first appeared. In the example, sewing was seen before bike, so it takes the second spot when both have one request.

Predict
Which category gets the second spot in most_common(2)?
- sewing
- bike

Worked example (example.py)

from collections import Counter

counts = Counter(["sewing", "battery"])
counts.update(["battery", "bike"])

print(counts["lamp"])
for category, count in counts.most_common(2):
    print(f"{category}: {count}")


Example result
0
battery: 2
sewing: 1

Read a line of space-separated category names. Make names lower case before counting. Print “Requests: ” with the total, then “Battery: ” with the battery count even when it is zero. Print up to two more lines as “Top category: N”, with the actual category and count. For a tie, use the order in which categories first appeared.

Starter program (starter.py)

import sys
from collections import Counter

categories = sys.stdin.readline().split()
counts = Counter(categories)
print(f"Requests: {counts.total()}")


Starter input
bike Sewing bike battery sewing

Hint
Build a Counter from the cleaned names. Unpack category and count in a loop over counts.most_common(2).

Case 1. Try the sample
Input
bike Sewing bike battery sewing
Expected output
Requests: 5
Battery: 1
Top bike: 2
Top sewing: 2

Case 2. Tied counts and a missing category
Input
sewing bike bike SEWING
Expected output
Requests: 4
Battery: 0
Top sewing: 2
Top bike: 2

Case 3. No requests
Input
   
Expected output
Requests: 0
Battery: 0

Stretch
Try defaultdict(list) from collections to keep the repair tag IDs for each category. Append each tag with groups[category].append(tag) and show the list for one category.

Reflect
Why would alphabetical sorting give a different result for the tied counts in the check?

Check your prediction
sewing They each have one request. Sewing entered the tally first, so it keeps the earlier position.
