Before, we printed out grades, like this:
grades = {"CSC": 87, "CIV": 100, "MAT": 95, "ESC": 95}
for subj, grade in grades.items():
print("I got", grade, "in", subj)
Suppose that instead, we want to print out all the subjects in which we got 95, all the subjects in which we got 87, and so on. There is no automatic way to do this -- we'll have to write a little function:
def get_subj_by_grade(grades, grade):
'''Return a list of all the keys in grades that correspond to the value grade'''
res = []
for subj, grade2 in grades.items():
if grade == grade2:
res.append(subj)
return res
Here is how we would use this function:
get_subj_by_grade(grades, 95)
get_subj_by_grade(grades, 97)
get_subj_by_grade(grades, 87)
We are now ready to iterate through the dictionary:
for grade in grades.values():
print("I got", grade, "in", get_subj_by_grade(grades, grade))