Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check the presence of many keys in a Python dictionary?

Tags:

python

I have the following dictionary:

sites = {
    'stackoverflow': 1,
    'superuser': 2,
    'meta': 3,
    'serverfault': 4,
    'mathoverflow': 5
}

To check if there are more than one key available in the above dictionary, I will do something like:

'stackoverflow' in sites and 'serverfault' in sites

The above is maintainable with only 2 key lookups. Is there a better way to handle checking a large number of keys in a very big dictionary?

like image 964
Thierry Lam Avatar asked May 11 '10 19:05

Thierry Lam


People also ask

How do you check the presence of a key in a dictionary?

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you count keys in a dictionary Python?

Python dictionary count keysBy using the len() function we can easily count the number of key-value pairs in the dictionary.

How do you know how many keys are in a dictionary?

We can use the keys() method of the dictionary to get a list of all the keys in the dictionary and count the total number using len() . We can also pass the dictionary directly to the len() function, which returns the distinct total entries in the dictionary, which is the same as the number of the keys.

How do you check if an item exists in a dictionary Python?

You can check if a key exists in a dictionary using the keys() method and IN operator. What is this? 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 .


1 Answers

You can pretend the keys of the dict are a set, and then use set.issubset:

set(['stackoverflow', 'serverfault']).issubset(sites) # ==> True

set(['stackoverflow', 'google']).issubset(sites) # ==> False
like image 140
Andrew Jaffe Avatar answered Oct 16 '22 02:10

Andrew Jaffe