Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list of keys exist in dictionary [duplicate]

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.

like image 801
applechief Avatar asked Jun 12 '12 10:06

applechief


People also ask

How do you check if a dictionary has a list of keys?

Using Keys() The keys() function and the "in" operator can be used to see if a key exists in a dictionary. The keys() method returns a list of keys in the dictionary, and the "if, in" statement checks whether the provided key is in the list. It returns True if the key exists; otherwise, it returns False.

Can a Python list have duplicate keys?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Do dictionaries have duplicate key values?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


2 Answers

Use all():

if all(name in grades for name in students):     # whatever 
like image 136
Sven Marnach Avatar answered Sep 24 '22 13:09

Sven Marnach


>>> grades = {         'alex' : 11,         'bob'  : 10,         'john' : 14,         'peter': 7 } >>> names = ('alex', 'john') >>> set(names).issubset(grades) True >>> names = ('ben', 'tom') >>> set(names).issubset(grades) False 

Calling it class is invalid so I changed it to names.

like image 24
jamylak Avatar answered Sep 24 '22 13:09

jamylak