Week 7
Week 7
# Function to invert the dictionary such that courses are keys and students are values
def invert_dictionary(student_courses):
# Create an empty dictionary to store the inverted structure
course_students = {}
return course_students
Technical Explanation:
The provided code defines a function invert_dictionary which takes a dictionary
student_courses as input. This dictionary has students as keys and a list of courses each student
is enrolled in as values. The goal of the function is to invert this dictionary, such that the keys
become the courses, and the values become lists of students enrolled in each course.
Here is a step-by-step explanation of the function:
1. Initialization: The function starts by creating an empty dictionary called
course_students which will store the inverted structure.
2. Iteration through the original dictionary: Using a for loop, the function iterates
through each student and their corresponding list of courses in the student_courses
dictionary.
3. Inner Iteration through the list of courses: For each student, another for loop iterates
through the list of courses they are enrolled in.
4. Checking and updating the inverted dictionary:
If a course (as a key) does not already exist in the course_students dictionary, it
is added with an empty list as its value.
The student is then appended to the list of students corresponding to the current
course.
5. Return the inverted dictionary: After processing all students and courses, the function
returns the course_students dictionary, which now has courses as keys and lists of
students as values.
When the invert_dictionary function is called with this input, the output is:
{
'CS1101': ['Stud1'],
'CS2402': ['Stud1', 'Stud2'],
'CS2001': ['Stud1', 'Stud2'],
'CS1102': ['Stud2']
}
This output correctly reflects the courses as keys and the students enrolled in each course as
values, meeting the teacher's requirement. The code includes comments to provide clarity on the
logic and steps involved, making it easier to understand for someone reviewing the code.
References:
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press.
Python Software Foundation. (2021). Python Language Reference, version 3.9. Available at
Python.org.
https://www.python.org