# Try this input too
grades = {
9: ["Amanda", "Bert"],
8: ["Charlie", "Denise"],
7: ["Ernesto", "Fiona", "Gonzalo"],
6: ["Hilda", "Ignacio", "Jerry"]
}Review: Invert Dictionary
Module 4: IDEs & Tools
Invert Dictionary
Write a Python program to invert a given dictionary with non-unique hashable values.
Example: - Input: d = {"fruit": ["apple", "pear"], "veggie": ["pepper"]} - Output: {"apple": "fruit", "pear": "fruit", "pepper": "veggie"}
Solution
Try the exercise on your own first, then compare with the worked solution below.
# Solution
def invert_dict(dict_in: dict) -> dict:
dict_out = {}
for key, ls in dict_in.items():
for value in ls:
dict_out[value] = key
return dict_out
students = invert_dict(grades)
print(students)