chaft chaft - 4 months ago 9
Python Question

Python check if list of keys exist in dictionary

I have a dictionary that looks like that:

grades = {
'alex' : 11,
'bob' : 10,
'john' : 14,
'peter': 7
}


and a list of names
students = ('alex', 'john')


I need to check that all the names in
students
exist as keys in
grades
dict.

grades
can have more names, but all the names in
students
should be in
grades


There must be a straightforward way to do it, but i'm still new to python and can't figure it out. tried
if students in grades
, didn't work.

In the actual cases, the lists will be much bigger.

Answer

Use all():

if all(name in grades for name in students):
    # whatever
Comments