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")
>Solution :
First test the key, then get the value (the list) associated with the key and test it.
You can do it like this:
student_dict = {
"student1": ["esports"],
"student2": ["football", "basketball"],
"student3": ["football"]
}
key = "student2"
value = "football"
if key in student_dict:
if value in student_dict[key]:
print("Sport present")