mardi 9 novembre 2021

Test Whether Specific Key and Value Exist in Dictionary Where Multiple Values Stored as Lists

I have a dictionary that sometimes contains multiple values per key. I want to test if both a specific key and specific value is present. I can do this where there are single values but cannot work out how to do it where multiple values exist in a list format.

So, in the example below the code should print "sport present" but it doesn't. Presumably I need to iterate through the list but how do I do this whilst also testing the key?

student_dict = {
    "student1": ["esports"],
    "student2": ["football", "basketball"],
    "student3": ["football"]
}

key = "student2"
value = "football"

if (key, value) in student_dict.items():
    print("Sport present")

Aucun commentaire:

Enregistrer un commentaire