Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Counting with dictionaries
6. Counting elements in tuples with dictionaries
Grouping with dictionaries
Linking with dictionaries
Summary

Instruction

Good! Now let's take a look at a similar example. This time, however, we'll have a list of tuples to make things a tiny bit more complicated:

votes = [
  ('John', 'Volvo'), ('Alice', 'Volvo'), ('Kate', 'BMW'), 
  ('Mary', 'Audi'), ('Mark', 'Audi'), ('Tim', 'Audi'), 
  ('Michael', 'BMW'), ('Samantha', 'Volvo'), ('Adrian', 'Volvo'), 
  ('Gray', 'Audi')
]
dict_results = {}
for vote in votes:
  _, car_make = vote
  if car_make not in dict_results:
    dict_results[car_make] = 0
  dict_results[car_make] += 1
print(dict_results)

In the example above, votes are no longer anonymous. Instead of strings with car makes, we get tuples with two strings: voter's names and car makes. We still want to count the number of votes for each car make. To that end, we unpack each tuple inside our for loop (_, car_make = vote). The rest of the code is very similar to what we had before.

Exercise

You are given two data structures:

  1. users – a list of forum users' names along with their nationalities (a list of tuples).
  2. nationality_to_continents – a dictionary in which nationalities are keys and continents are values.

Create a dictionary named users_continents and use it to store the number of users for each continent in a following form:

users_continents = {'Europe': 3, 'Asia': 4, 'North America': 2}

Stuck? Here's a hint!

Your code should be very similar to that shown in the explanation.