chaft chaft - 1 year ago 177
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
exist as keys in

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

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 Source

Use all():

if all(name in grades for name in students):
    # whatever
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download