Problem overview
Version 5 keeps each score under its subject name, in a dictionary: grades = {"Math": 92, "English": 78, "Science": 85, "History": 67}. The program must print every subject with its letter grade, in alphabetical order, in the form subject: grade. The scale is the one from the earlier versions: 90 and above is an A, 80 to 89 a B, 70 to 79 a C, 60 to 69 a D, and anything lower an F.
The expected output is:
English: C
History: D
Math: A
Science: B
The lines are not in the order the dictionary was written in. Alphabetical order puts English first and Science last.
Approach: sort the keys, look up each score, apply the ladder
With a dictionary there are no positions to count. The keys are the subject names, and a key gives access to its value. So the loop goes over the keys, and each key is used to fetch the score.
The order needs care. Looping over a dictionary directly visits the keys in the order they were inserted, here Math, English, Science, History, which is not what the lesson wants. The function sorted(grades) takes the keys and returns a new list of them in alphabetical order: ['English', 'History', 'Math', 'Science']. Looping over that list gives the required order, and the dictionary itself is left unchanged.
Inside the loop, the grading ladder is the same as in the previous version: it tests the highest grade first, so each later test needs only a lower limit.
Step by step
- Loop over the sorted keys:
for subject in sorted(grades):. On each pass,subjectis one subject name. - Look up the score:
score = grades[subject]. The key gives back the value stored under it. - Start the ladder with
if score >= 90:and setgrade = "A". - Add
elif score >= 80:for"B". Only scores below 90 get this far. - Add
elif score >= 70:for"C". - Add
elif score >= 60:for"D". - End with
else:for"F", which covers every score below 60. - Print the line inside the loop, after the ladder: the subject,
": "andgrade. It is indented inside the loop, so it prints once per subject.
The solution in Python
grades = {"Math": 92, "English": 78, "Science": 85, "History": 67}
for subject in sorted(grades):
score = grades[subject]
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(subject + ": " + grade)
Details worth knowing:
sorted()returns a list. Handing it a dictionary sorts the keys only. If you also need the scores, either look them up as the solution does, or sortgrades.items(), which gives(subject, score)pairs in key order.- Dictionaries remember insertion order, but that is not alphabetical order.
list(grades)gives['Math', 'English', 'Science', 'History'], the order in which the keys were written. Sorting is what makes the output predictable. - Sorting is case-sensitive. Strings compare by character code, and capital letters come before lowercase ones.
sorted(["math", "Science", "English"])gives['English', 'Science', 'math']. The lesson's subjects all start with a capital letter, so this does not show up here. grades[subject]is safe here. The keys come from the dictionary itself, so each lookup succeeds. Looking up a name that is not a key, such asgrades["Art"], raises aKeyError, whilegrades.get("Art", 0)returns the default 0 instead.
How the loop runs on the example
sorted(grades) is evaluated once, before the loop starts, and gives ['English', 'History', 'Math', 'Science']. On the first pass subject is "English", and grades["English"] is 78. The first two tests fail, 78 >= 70 passes, and the program prints English: C. On the second pass, "History" has 67, which reaches the D branch. "Math" has 92 and takes the first branch. "Science" has 85 and takes the second.
The score is stored once, under one key. Nothing needs to be kept in step with a second list, and that is the benefit of the dictionary over the parallel lists of the previous version: there is no position to get wrong, because the name and the score travel together.
A loop can also unpack the pairs directly: for subject, score in sorted(grades.items()): gives the same four pairs in the same order, with the score already in hand. The lesson's steps use the key-then-lookup form, which shows plainly what a dictionary does.
Edge cases and common mistakes
- Looping without
sorted.for subject in grades:works but prints Math first, which breaks the required order. - Looking for a position. A dictionary has no
grades[0]. A number is treated as a key, and 0 is not a key here. - Leaving out the
else. Without it, a failing score would leavegradeholding the previous subject's letter. - A repeated subject. A dictionary keeps one value per key, so if
"Math"were written twice in the literal, only the later score would remain and Math would be printed once. - An empty dictionary.
sorted({})is an empty list, so the loop body never runs and nothing is printed.
Testing
With {"art": 95, "Biology": 50}, the program prints Biology: F and then art: A. The lowercase key sorts after the capitalised one, because of the case rule above.
