Counting with dictionaries, explained simply
Imagine counting class votes for a trip: beach, zoo, beach, museum, beach. You make a tally mark next to each place as you read the votes. A dictionary can keep that tally for you.
Loop through the votes. For each one, if it is not yet in the dictionary, start it at 0. Then add 1. At the end each key holds how many times it appeared.
.get(key, 0) combines both steps: it gives the current count, or 0 if the key is new.
Example: Tally the votes
votes = ["beach", "zoo", "beach", "museum", "beach"]
tally = {}
for place in votes:
tally[place] = tally.get(place, 0) + 1
print(tally)Output
{'beach': 3, 'zoo': 1, 'museum': 1}Try this
- Count the letters in your name.
- Find the winner by looping through the tally and remembering the biggest count.
- Count the words in a sentence using .split() to break it into a list first.
