Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading