11.8 Accumulating the Best Key

From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period3 exercises4 graded tests

README.md

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.

Exercise 1

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

Open the 01 folder and edit main.py. This one is not graded, so check it yourself.

Check your Understanding

Exercise 2

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.

Open the 02 folder and edit main.py. Run Tests checks it.

Exercise 3

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.

Open the 03 folder and edit main.py. Run Tests checks it.

For teachers

11.8 Accumulating the Best Key

Students read Foundations of Python Programming's “Accumulating the Best Key” in CS Room and work through its 3 Python coding exercises (2 graded).

  • Time: 1 class period
  • Tests: 4 in 2 graded exercises, set up for you when you import the lesson

Exercises

FolderGradingTests
01Not graded; students check it themselves0
02Autograded2
03Autograded2