01 / 07
The shape you used to write for counting
Say you want to know how many times each colour came up. Think back to how Chapter 2 did it.
You make an empty dictionary, run a for over the values, and put a 1 in if the key is not there yet, or add 1 if it is. These six lines should look familiar.
They run, and they read well enough. But writing the same six lines every time you need something as ordinary as counting is a chore.
words = ["red", "blue", "red", "yellow", "red", "blue"]counts = {}for w in words: if w in counts: counts[w] += 1 else: counts[w] = 1print(counts)Result
{'red': 3, 'blue': 2, 'yellow': 1}