I have a fixed list of strings. I need to check if any of these strings are a key in the dictionary (just need True or False). I could go
if 'asdf' in dict or 'qwer' in dict or 'zxcv' in dict ... : ... do important secret stuff ...
but it seems suboptimal. Is there a more idiomatic way of doing this?
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.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.
Check If Key Exists using the Inbuilt method keys() Using the Inbuilt method keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use if statement with 'in' operator to check if the key is present in the dictionary or not.
You could use any
and iterate over each key you want to check
if any(key in dict for key in ['asdf', 'qwer', 'zxcf']):
# contains at least one of them
This will short-circuit and return True
upon finding the first match, or will return False
if it finds none.
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