Programming Assignment Unit 7
Inverting a Dictionary in Python
Introduction
Dictionaries are one of the most useful data structures in
Python because they store information using key-value
pairs. In this assignment, a dictionary is used to store
students and the courses they are enrolled in. The
objective is to invert the dictionary so that the courses
become the keys and the students become the values.
This type of transformation is useful when teachers want
to know which students are enrolled in each course.
The program below uses loops and dictionaries to create
a new inverted dictionary. Each course is checked, and
the student’s name is added to the correct course list. If
the course does not already exist in the new dictionary,
the program creates a new entry first.
Python Program
Output
Technical Explanation
This program demonstrates how dictionaries can be manipulated in Python.
The original dictionary stores student names as keys and lists of courses as
values. The goal of the program is to reverse the structure of the dictionary
so that courses become the keys and students become the values.
The function named invert_dictionary() is created to perform this task. Inside
the function, an empty dictionary called inverted is initialized. The program
uses the items() method to loop through both the student names and their
course lists at the same time.
A nested loop is then used to go through each individual course in the course
list. For every course, the program checks whether the course already exists
in the inverted dictionary. If the course is not present, a new empty list is
created for that course. After that, the student’s name is appended to the list
of students enrolled in the course.
The output shows both the original dictionary and the inverted dictionary.
This makes it easy to compare the data structures before and after the
transformation. The program is efficient because it organizes course
information clearly and allows teachers to quickly identify which students are
enrolled in each course.
This assignment also demonstrates important Python concepts such as
dictionaries, loops, functions, lists, and the items() method.
References
Downey, A. (2015). Think Python: How to think like a computer scientist (2nd
ed.). Green Tea Press. [Link]�
Raj, A. (2022). Reverse a dictionary in Python. PythonForBeginners.
[Link]�
[Link]�