Very well done! We can actually make the code from the previous exercises a bit easier if we use the get()
function. See for yourself:
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
dict_results[car_make] = dict_results.get(car_make, 0) + 1
print(dict_results)
In the code above, dict_results.get(car_make, 0)
means "take the value associated with the car_make
key from dict_results
. If it doesn't exist, take 0 instead." This way, we can skip checking if a given key exists.