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)]
Counter(orders)counts how many times each item of the list appears. The result is a special dictionary: the keys are the item names, the values are how many times each item appears. When it is printed, that dictionary is written insideCounter(...).counts["iced orange"]gives0for an item that was never ordered. An ordinary dictionary would fail with aKeyError.most_common(2)gives the 2 most ordered items, from the most ordered down. The result is a list of(item, count)tuples. Without a number,most_common()gives every item.- When two items have the same count,
most_commonorders them by which one appears first in the list.
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:
for name, class_name, score in students:unpacks the student's tuple into three variables.- If that class has no basket yet (
class_name not in groups), make an empty list for it. - 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
statistics.mean(numbers)adds up all the numbers, then divides by how many there are: (88 + 92 + 79) / 3 = 86.33...:.1ffrom the Strings in Python lesson shows the average rounded to one digit after the dot.- The result of
meanis not always a decimal number:statistics.mean([80, 90])gives85, not85.0. When every result must be shown in the same form, format it with:.1f. statistics.median(numbers)gives the middle value: the number in the middle once all the numbers are sorted. For example,statistics.median([75, 64, 90])is75, because the sorted order is 64, 75, 90.
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
appendto a group that was never made.groups[class_name].append(score)on an empty dictionary fails withKeyError: '8A'. Make an empty list first, or usedefaultdict(list).- Giving Counter one string.
Counter("tea")counts each letter:Counter({'t': 1, 'e': 1, 'a': 1}). Send a list of item names, not one piece of text. - The average of an empty list. A class with no scores makes
statistics.mean([])fail. In the exercise, the error isStatisticsError: mean requires at least one data point. In a terminal,python3writes its full name,statistics.StatisticsError. Check first that the list is not empty. - Counter for adding up. Counter counts how many times something appears. To add up numbers per group, use
total.get(item, 0) + quantity.
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.