Suppose we want to "invert" the grades dictionary: to have grades as keys, and the subjects in which we've got the grades as the values (since there may be more than one, we'll store lists of subjects). This is similar to creating a "reverse phone book" out of a regular phone book.
grades = {"CSC": "A", "PHY": "B+", "MAT":"A+", "ESC":"A+"}
Our goal is to create the following list:
inv_grades = {"A": ["CSC"], "B+": ["PHY"], "A+":["MAT", "ESC"]}
def get_inv_grades(grades):
inv_grades = {}
#Iterate over course, grade in grades, create a new list if grade isn't
#in inv_grades yet, or append to an existing list if grade has already
#been encountered
for course, grade in grades.items():
if grade not in inv_grades:
inv_grades[grade] = [course]
else:
inv_grades[grade].append(course)
return inv_grades