Accumulating the Best KeyΒΆ

Now what if we want to find the key associated with the maximum value? It would be nice to just find the maximum value as above, and then look up the key associated with it, but dictionaries don’t work that way. You can look up the value associated with a key, but not the key associated with a value. (The reason for that is there may be more than one key that has the same value).

The trick is to have the accumulator keep track of the best key so far instead of the best value so far. For simplicity, let’s assume that there are at least two keys in the dictionary. Then, similar to our first version of computing the max of a list, we can initialize the best-key-so-far to be the first key, and loop through the keys, replacing the best-so-far whenever we find a better one.

In the exercise below, we have provided skeleton code. See if you can fill it in. An answer is provided, but you’ll learn more if you try to write it yourself first.

Write a program that finds the key in a dictionary that has the maximum value. If two keys have the same maximum value, it’s OK to print out either one. Fill in the skeleton code

Next Section - Exercises