Counting & Grouping — Python

counts = Counter(items) (from the built-in collections module) counts how many times each item of a list appears. counts["item"] gives 0 for something that…

In the evening, after the stall closes, Mr. Darto wants to know which items sold best. Mrs. Rina, a form teacher at the school next door, has a similar question: what is the average score of each class? Both questions follow the same pattern. The data is a long list, and the answer comes from counting and grouping.

Grouping is like sorting laundry into baskets. Each basket has a label (class 8A, class 8B), and each piece of clothing (one student's score) goes into the basket whose label is that student's class. In Python, all those baskets are kept in one dictionary. The basket's label is the key, and what is in the basket (a list of scores) is the value. Once every score is in a basket, you can work with what is in each one, for example calculate its average.

Counting with Counter

In the Dictionaries lesson, you counted orders with counts.get(item, 0) + 1. Python has a shortcut for that job: Counter from the built-in collections module.

from collections import Counter

orders = ["coffee with milk", "sweet tea", "coffee with milk", "toast", "coffee with milk", "sweet tea"]
counts = Counter(orders)
print(counts)
print(counts["coffee with milk"], counts["iced orange"])
print(counts.most_common(2))

The output:

Counter({'coffee with milk': 3, 'sweet tea': 2, 'toast': 1})
3 0
[('coffee with milk', 3), ('sweet tea', 2)]

Grouping with a dictionary of lists

Mrs. Rina has a list of students. Each student is written as a tuple (name, class_name, score). To calculate the average per class, the scores are first collected per class. In this code, groups is the dictionary of baskets: its keys are the classes, its values are lists of scores.

students = [("Sari", "8A", 88), ("Budi", "8B", 75), ("Rina", "8A", 92), ("Dodi", "8B", 64), ("Tono", "8A", 79)]

groups = {}
for name, class_name, score in students:
    if class_name not in groups:
        groups[class_name] = []
    groups[class_name].append(score)

print(groups)

The output:

{'8A': [88, 92, 79], '8B': [75, 64]}

The steps inside the loop, for each student:

  1. for name, class_name, score in students: unpacks the student's tuple into three variables.
  2. If that class has no basket yet (class_name not in groups), make an empty list for it.
  3. Put the student's score into the class's list with append.

Step 2 is required. Without it, groups[class_name].append(score) fails for the first student with KeyError: '8A', because class 8A has no list yet.

The average of each group: statistics.mean

Once the scores are collected, calculate each class's average with statistics.mean (mean means average). statistics is also a built-in Python module:

import statistics

groups = {"8A": [88, 92, 79], "8B": [75, 64]}
for class_name, scores in groups.items():
    average = statistics.mean(scores)
    print(f"{class_name}: average {average:.1f}, highest {max(scores)}")

The output:

8A: average 86.3, highest 92
8B: average 69.5, highest 75

Adding up per group

Counter counts how many times something appears. Sometimes each record carries its own quantity, for example "coffee with milk, 3 cups". For records like those, add them up with get as in the Dictionaries lesson:

sales = [("coffee with milk", 3), ("sweet tea", 2), ("coffee with milk", 1), ("toast", 2)]

total = {}
for item, quantity in sales:
    total[item] = total.get(item, 0) + quantity

print(total)

The output:

{'coffee with milk': 4, 'sweet tea': 2, 'toast': 2}

Counter(sales) cannot be used here. Counter would count each tuple as one item of the list. So ("coffee with milk", 3) and ("coffee with milk", 1) would be counted as two different items, each appearing once, and the 3 and the 1 would not be added up.

📌 defaultdict: baskets that make themselves

defaultdict from collections can make an empty list by itself when a key is used for the first time. So the line if class_name not in groups is not needed:

from collections import defaultdict

students = [("Sari", "8A"), ("Budi", "8B"), ("Rina", "8A")]
groups = defaultdict(list)
for name, class_name in students:
    groups[class_name].append(name)

print(dict(groups))

The output:

{'8A': ['Sari', 'Rina'], '8B': ['Budi']}

defaultdict(list) means: if the key does not exist yet, give that key the value list(), which is an empty list. dict(groups) turns it into an ordinary dictionary, so that only its contents are printed, without defaultdict(<class 'list'>, ...) around them.

⚠️ A basket that does not exist yet, and letters that get counted

TL;DR: counts = Counter(items) (from the built-in collections module) counts how many times each item of a list appears. counts["item"] gives 0 for something that never appeared, and most_common(n) on counts gives the n most common (item, count) pairs. Grouping means collecting data per group, for example students' scores per class. To group, use a dictionary of lists: the keys are the group names, the values are lists of each group's data. If the key does not exist yet, make an empty list first, then append. Without that empty list, the result is a KeyError. defaultdict(list), also from collections, makes the empty list by itself. statistics.mean(numbers) gives the average, and statistics.median(numbers) the middle value. mean of an empty list fails with a StatisticsError. To add up numbers per group in a dictionary total, use total.get(key, 0) + quantity.

⚡ Counting with Counter

Write:

from collections import Counter

orders = ["coffee with milk", "sweet tea", "coffee with milk", "toast", "coffee with milk", "sweet tea"]
counts = Counter(orders)
print(counts)
print(counts["coffee with milk"], counts["iced orange"])
print(counts.most_common(2))
Guess first: Counter counts how many times each item appears in the list orders. Iced orange was never ordered. What is counts["iced orange"]?

0. Counter gives 0 for something that never appeared, with no KeyError. The second line of the output is 3 0.

Meaning: Counter(items) from the built-in collections module counts how many times each item of a list appears. most_common(2) gives the two items that appear most often, as (item, count) pairs: [('coffee with milk', 3), ('sweet tea', 2)].

⚡ Groups with a dictionary of lists

Write:

students = [("Sari", "8A", 88), ("Budi", "8B", 75), ("Rina", "8A", 92), ("Dodi", "8B", 64), ("Tono", "8A", 79)]

groups = {}
for name, class_name, score in students:
    if class_name not in groups:
        groups[class_name] = []
    groups[class_name].append(score)

print(groups)

Meaning: This code collects the students' scores per class. Each student is a tuple (name, class_name, score). The result is a dictionary with the class as key and a list of scores as value: {'8A': [88, 92, 79], '8B': [75, 64]}. A class that appears for the first time gets an empty list first. Without that if line, the first append fails with KeyError: '8A'.

⚡ The average with statistics.mean

Guess first: statistics.mean([88, 92, 79]) gives the average score of class 8A, and the result is stored in average. Printed with f"{average:.1f}", what is it?

86.3. The average is (88 + 92 + 79) / 3 = 86.33..., and :.1f shows it rounded to one digit after the dot.

Meaning: statistics.mean(numbers) from the built-in statistics module gives the average of a list of numbers, and statistics.median(numbers) its middle value. For an average per group, run mean on each group's list. An empty list makes mean fail with a StatisticsError.

⚡ Adding up per group

Meaning: Sometimes each sales record carries its own quantity, for example the tuple ("coffee with milk", 3): the item's name and the number of cups. To add these up per item, unpack each tuple into item and quantity, then add to a dictionary total: total[item] = total.get(item, 0) + quantity. Counter only counts how many times something appears, so it cannot add up numbers like these.

What you will learn