Counting and grouping
Counting how many times each thing appears is one of the most common jobs for a dictionary. The things become the keys, and their counts the values:
colors = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for color in colors:
if color not in counts:
counts[color] = 0
counts[color] += 1
print(counts)
{'red': 3, 'blue': 2, 'green': 1}not in is the opposite of in: it's true when the key is not in the dictionary. The first time a color comes up, it isn't a key yet, so the loop adds it with the count 0. Then, every time, its count goes up by one.
Without the if, the very first += stops the program. += reads the old value before it adds to it, and there is no old value yet:
colors = ["red", "blue"]
counts = {}
for color in colors:
counts[color] += 1
Traceback (most recent call last):
File "main.py", line 4, in <module>
counts[color] += 1
~~~~~~^^^^^^^
KeyError: 'red'Grouping
The same pattern can sort things into groups. The values are lists, and each thing is appended to the list of its group. Here students are grouped by their grade:
results = [["Ada", 5], ["Max", 3], ["Lin", 5], ["Kim", 4], ["Bo", 3]]
by_grade = {}
for result in results:
name = result[0]
grade = result[1]
if grade not in by_grade:
by_grade[grade] = []
by_grade[grade].append(name)
for grade in sorted(by_grade):
print(grade, by_grade[grade])
3 ['Max', 'Bo']
4 ['Kim']
5 ['Ada', 'Lin']The first time a grade comes up, it gets an empty list. Then the name goes into the list of its grade. Both patterns have the same shape: make sure the key exists, then update its value.