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

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

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

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