11.8. 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
Check your Understanding
1. Create a dictionary called d
that keeps track of all the characters in the string placement
and notes how many times each character was seen. Then, find the key with the lowest value in this dictionary and assign that key to key_with_min_value
.
5. Create a dictionary called lett_d
that keeps track of all of the characters in the string product
and notes how many times each character was seen. Then, find the key with the highest value in this dictionary and assign that key to key_with_max_value
.