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.

JavaScript

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?

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement