What would be the Pythonic way to check if ANY element in a list is a key in a dictionary?
Example, I have a list of fruits:
fruits = ['apples', 'bananas', 'pears']
And want to check if ANY fruit is a key in my dictionary, examples:
fruit_dict1 = {'apples': 4, 'oranges': 3, 'dragonfruit': 4} returns True
fruit_dict2 = {'oranges': 3, 'dragonfruit': 9, 'pineapples': 4} returns False
So far I have:
def fruit_checker(list, dict):
for fruit in list:
if fruit in dict:
return True
return False
It feels weird to just look for a fruit "in" a dictionary, but it seems "in" only does a search on dictionary keys. How exactly does "in" work with the different types?
You can check if a key exists in a dictionary using the keys() method and IN operator. The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .
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.
To get the value for the key, use dict[key] . dict[key] raises an error when the key does not exist, but the get() method returns a specified value (default is None ) if the key does not exist.
python check if key in dictionary using try/except If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError. This can also be a way to check if exist in dict or not i.e. Here it confirms that the key 'test' exist in the dictionary.
Try this
In [1]: any([i in fruit_dict1 for i in fruits])
Out[1]: True
In [2]: any([i in fruit_dict2 for i in fruits])
Out[2]: False
Working
In [11]: [i in fruit_dict2 for i in fruits]
Out[11]: [False, False, False]
Which check the every element present. And return a list of boolean values and any
will return if any True
is exist.
In [13]: any([True,False,False])
Out[13]: True
set(fruits) & set(fruit_dict1.keys())
or using Counter
from collections import Counter
any(Counter(fruits) & Counter(fruit_dict1.keys()))
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