Back-To-School Deals - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Counting with dictionaries
8. Summing up values
Grouping with dictionaries
Linking with dictionaries
Summary

Instruction

Good job! Now let's analyze a slightly modified example of counting elements.

Suppose we have a list with game results. Each person can take part in one or more games and win from 0 to 10 points in each game. The list presents all points that the participants collected:

game_results = [
  ('John', 9), ('Mike', 8), ('Anne', 5), ('Anne', 10),
  ('Kate', 8), ('Kate', 7), ('John', 3), ('Anne', 6)
]

Our task is to sum up the points for each person and present the results as a dictionary. Take a look:

dict_results = {}
for result in game_results:
  name, points = result
  dict_results[name] = dict_results.get(name, 0) + points
print(dict_results)

Result:

{'John': 12, 'Mike': 8, 'Anne': 21, 'Kate': 15}

As you can see, the code is very similar to the previous exercise. The only difference is that we don't add 1 each time. Instead, we add the number of points which we unpacked from the result tuple.

Exercise

Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

Stuck? Here's a hint!

Sum up jump lengths and number of jumps in a way similar to the explanation code. Then, iterate over the keys and divide the sum of jumps lengths by the number of jumps.