Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if any element in a list is a key in dictionary

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?

like image 842
devonj Avatar asked Jul 07 '16 06:07

devonj


People also ask

How do you check if any element of a list is a key in dictionary?

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 .

How do you check if a dictionary key is in a list Python?

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.

How do you check if a value is a key in a dictionary Python?

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.

How do you check a key is exists in dictionary or not with out through KeyError?

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.


2 Answers

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
like image 155
Rahul K P Avatar answered Oct 17 '22 08:10

Rahul K P


set(fruits) & set(fruit_dict1.keys())

or using Counter

from collections import Counter
any(Counter(fruits) & Counter(fruit_dict1.keys()))
like image 39
SuperNova Avatar answered Oct 17 '22 09:10

SuperNova