You are on page 1of 3

Assignment Unit 7

By the instructions the dictionary key and values are as follow;

def invert_courses(student_course):

inverted = {}

# Initialize an empty dictionary.

for student, courses in student_course.items():

for course in courses:

if course in inverted:

inverted[course].append(student)

else:

inverted[course] = [student]

return inverted

# Example :

student_course = {

"Stud1": ["CS1101", "CS1102"],

"Stud2": ["CS1101", "C2203"],

"Stud3": ["C1102", "C2204"]

inverted_courses=invert_courses(student_course)

print(inverted_courses)

The code takes an input dictionary where students are keys, and their courses are

values. In this example, there are three students (Stud1, Stud2, and Stud3) and the
courses they are enrolled in. The output of the code, when using the provided example,

would be:

'CS1101': ['Stud1', 'Stud2'],

'CS1102': ['Stud1', 'Stud3'],

'CS2203': ['Stud2'],

'CS2204': ['Stud3']

CS1101 course has 'Stud1' and 'Stud2' enrolled.

CS1102 course has 'Stud1' and 'Stud3' enrolled.

CS2203 course has 'Stud2' enrolled.

CS2204 has 'Stud3' enrolled.

This inverted dictionary now satisfies the tneed, with courses as keys and lists of

students as values, as instructed. It allows to easily see which students are enrolled in

each course.

References

1. Downey, A. (2015). Think Python: How to think like a computer scientist (2nd

ed.). Green Tea Press.

2. kjdElectronics. (2017, August 5). Python beginner tutorial 8 - For loop, lists, and

dictionaries [Video]. YouTube. https://youtu.be/bE6mSBNp4YU

3. Raj, A. (2022, March 3). Reverse a dictionary in Python. PythonForBeginners.

4. Python Dictionaries. (n.d.). W3schools.

You might also like