
Counting with dictionaries
5. Counting elements with dictionaries
Grouping with dictionaries
Linking with dictionaries


Good job! We typically use dictionaries to count how many times a given item appears in a list. Take a look:

votes = ['Volvo', 'Volvo', 'BMW', 'Audi', 'Audi', 'Audi', 'BMW', 'Volvo', 'Volvo', 'Audi']
results = {}
for vote in votes:
  if vote not in results:
    results[vote] = 0
  results[vote] += 1

In the code above, we have a list with responses to the question "What's your favorite car make?" We want to count the number of votes for each make. To that end, we create an empty dictionary (results = {}) and iterate over the elements of the votes list. Each car make is a separate key in the dictionary, and its value reflects the number of votes it received. If a given car make has not appeared yet, we create a new entry in the dictionary. Then, we add 1 to the counter for that specific car make.


The mayor of a small town decided to change the town's name to attract more tourists. Three names were suggested: Screamer, Smackover, and Hazardville. The votes list contains all the citizens' votes. Your job is to:

  1. Count the number of votes for each name and store the results in a variable named counted_votes.
  2. Find the name with the most votes and print the following:
    {name} is the winning name!

Stuck? Here's a hint!

To solve the first part of the problem, use the code from the explanation. To solve the second part of the problem, iterate over the keys and values with counted_votes.items().