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.