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.
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.
Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
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.
Use all()
:
if all(name in grades for name in students): # whatever
>>> 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With