Counting with a Dictionary
Dictionaries are great for counting. Say a class is voting on where to go on a school trip, and you have the votes in a list:
votes = ["zoo", "castle", "zoo", "aquapark", "zoo", "castle"]How many votes did each place get? Make a dictionary in which the keys are the places and the values are their numbers of votes. Start with an empty dictionary and go through the votes one by one. When the place is already in the dictionary, add 1 to its number; when it isn't there yet, add it with the number 1:
votes = ["zoo", "castle", "zoo", "aquapark", "zoo", "castle"]
counts = {}
for vote in votes:
if vote in counts:
counts[vote] += 1
else:
counts[vote] = 1
print(counts){'zoo': 3, 'castle': 2, 'aquapark': 1}Why the if? On the first vote, "zoo" isn't in counts yet. counts[vote] += 1 would first have to read counts["zoo"], and the program would end with KeyError: 'zoo'.
With .get(), you can write the same thing in a single line. counts.get(vote, 0) gives the number of votes the place has so far, or 0 if it isn't in the dictionary yet. You add 1 to it and store the result under the same key:
votes = ["zoo", "castle", "zoo", "aquapark", "zoo", "castle"]
counts = {}
for vote in votes:
counts[vote] = counts.get(vote, 0) + 1
print(counts){'zoo': 3, 'castle': 2, 'aquapark': 1}Both versions do the same; use the one you understand better. You'll often see the shorter one in other people's code.
The same works for anything you can go through with a for loop: the words in a list, or the letters of a text.
Instructions
Count how many times each letter appears in word. Create an empty dictionary counts, go through the word letter by letter with a for loop and count the letters as in the example. Then print counts: {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}.
Below, go through counts with .items() and print the letters that appear more than once, each with its number, for example a: 5.
Start programming for free
6/9