Skip to content
Advertisement

How do I print a dictionary’s keys based on its value?

So, I’ve created a dictionary of key, value pairs for course name and student ID respectively. I want to be able to iterate through the dictionary and print all of the keys (course names) that contain a particular value (student ID).

So, here’s the first initialization of variables followed by asking the user to input a student ID. They can choose from 1001-1004.

def main():
    c_roster = {'CSC101': ['1004', '1003'],
                'CSC102': ['1001'],
                'CSC103': ['1002'],
                'CSC104': []}

    id_ = input('What is the student ID? ')
    list_courses(id_, c_roster)

And here I am iterating through the dictionary view and creating a list of keys that have a value that matches the id_ variable, and then printing that list. However, no matter which student ID I choose it keeps printing me an empty list. Why is this happening?

def list_courses(id_, c_roster):
    print('Courses registered:')
    c_list = [k for k, v in c_roster.items() if id_ == v]
    print(c_list)

main()

Advertisement

Answer

The list comprehension k, v in c_roster.items() returns k, v pairs such that k is the course name and v is the list of student IDs registered for that class.

Therefore you are comparing the ID id_ to a list of student IDs, which will never be true.

You will have to see if id_ is in v, like

c_list = [k for k, v in c_roster.items() if id_ in v]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement