You are on page 1of 3

:This is the Python code to reverse a dictionary and create the inverted dictionary

Original dictionary #

{ = students_courses

,Stud1': ['CS1101', 'CS2402', 'CS2001']'

Stud2': ['CS2402', 'CS2001', 'CS1102'] '

Create the inverted dictionary #

}{ = inverted_dict

:)(for student, courses in students_courses.items

:for course in courses

:if course in inverted_dict

inverted_dict[course].append(student)

:else

inverted_dict[course] = [student]
Print the original dictionary #
print("Original Dictionary:")

print(students_courses)

Print the inverted dictionary #


print("\nInverted Dictionary:")

print(inverted_dict)

:Explanation

We define the dictionary students_courses, which contains lists of students and their

.courses

.Then, we create an empty dictionary called inverted_dict to store the inverted dictionary
We iterate through each item in students_courses and examine each course in the student's

.associated courses list


If the course is already in inverted_dict, we add the student's name to the list of names

.associated with that course


If the course is not yet in inverted_dict, we create a new key and add the student's name as

.the first value

.Finally, we print both the original dictionary and the inverted dictionary

:The output

:Original Dictionary

}Stud1': ['CS1101', 'CS2402', 'CS2001'], 'Stud2': ['CS2402', 'CS2001', 'CS1102']'{

:Inverted Dictionary

CS1101': ['Stud1'], 'CS2402': ['Stud1', 'Stud2'], 'CS2001': ['Stud1', 'Stud2'], 'CS1102': '{
}['Stud2']

You might also like