Count with a Dictionary and get()
To count with a dictionary, store each value as a key and how often it appears as its value. get() reads a count, or gives 0 for a new value.
Before this lesson you should know how to read and change a dictionary value by its key: see Dictionaries.
Read a value with a default
counts.get(key, 0) gives the key's value. When the key is missing, it gives
the second argument, 0, instead:
counts = {"shell": 2}print(counts.get("shell", 0))print(counts.get("crab", 0))It printed 2, then 0. counts["crab"] would raise a KeyError, because
there is no "crab" key.
Start from an empty dictionary
{} is a dictionary with no keys yet. Every key is missing, so get() gives
the default:
counts = {}print(counts)print(counts.get("shell", 0))It printed {}, then 0. Reading with get() does not add a key: counts
is still empty.
Add one to a count
Read the old count with get(), add 1, and store it back under the same key.
The same line works the first time and every time after:
counts = {}counts["shell"] = counts.get("shell", 0) + 1print(counts)counts["shell"] = counts.get("shell", 0) + 1print(counts)It printed {'shell': 1}, then {'shell': 2}. The first time, get() gave
0, so the count started at 1.
Count every value in a list
Put that line in a loop over the list. Each value adds one to its own count:
colours = ["red", "blue", "red", "red"]counts = {}for colour in colours: counts[colour] = counts.get(colour, 0) + 1print(counts)It printed {'red': 3, 'blue': 1}. The keys are in the order each value was
first seen: "red" came before "blue".
See also: Dictionaries, The Accumulator Pattern.
Your turn
Add two lines: a for loop over votes that adds one to each vote's count
with get().
{'cat': 2, 'dog': 1}votes = ["cat", "dog", "cat"]counts = {}# add a for loop that counts each vote with get()print(counts)