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?
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.
Python dictionary count keysBy using the len() function we can easily count the number of key-value pairs in the 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.
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 .
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
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