Counting and Grouping
A dictionary is how you count things, and how you split a table into groups.
Counting with a dictionary
The key is the thing being counted and the value is how many you have seen. .get with a default of 0 is what keeps the first sighting from raising.
subjects = ["maths", "computing", "maths"]
counts = {}
for s in subjects:
counts[s] = counts.get(s, 0) + 1
print(counts)
Grouping is counting with lists
Same shape, except the value is a list you append to instead of a number you add to. This is the whole idea behind every group-by you will meet later.
rows = [("maths", 92), ("computing", 88), ("maths", 79)]
groups = {}
for subject, score in rows:
groups.setdefault(subject, []).append(score)
print(groups)
Exercise
Try It YourselfWrite count_subjects(rows) that takes a list of (subject, score) pairs and returns a dictionary of how many rows each subject has.
Press Run to see output