Test whether specific key and value exist in dictionary where multiple values stored as lists

Viewed 43

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")
4 Answers

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

First, you can create list for all value with key then check as you want:

>>> lst_key_values = [(key,v) for key,val in student_dict.items() for v in val]
>>> lst_key_values
[('student1', 'esports'),
 ('student2', 'football'),
 ('student2', 'basketball'),
 ('student3', 'football')]

>>> key = "student2"
>>> value = "football"
>>> if (key, value) in lst_key_values:
    print("Sport present")

Sport present

The code you wrote would only work if both values "football" and "basketball" are assigned to "value":

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

key = "student2"
value = ["football", "basketball"]

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

But if you want to test only for one value, then you should use the answer that jfaccioni provided.

You can use dict.get with a default return:

if value in student_dict.get(key, []):
    print("Sport present")
Related