In this article we will discuss 6 different ways to check if key exists in dictionary in python.
Suppose we have a dictionary of string and int i.e. Now we want to check if key ‘test’ exist in this dictionary or not. There are different ways to do this. Let’s discuss them one by one. Advertisements We can directly use the ‘in operator’ with the dictionary to check if a key exist in dictionary or nor. The expression, Will evaluate to a boolean value and if key
exist in dictionary then it will evaluate to True, otherwise False. Let’s use this to check if key is in dictionary or not. For example, # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'test' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") Output: Yes, key: 'test' exists in dictionary Here it confirms that the key ‘test’ exist in the dictionary. Now let’s test a negative example i.e. check if key ‘sample’ exist in the dictionary or not i.e. # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'sample' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") Output: No, key: 'sample' does not exists in dictionary Here it confirms that the key ‘sample’ does not exist in the dictionary. Python: check if dict has key using get() functionIn python, the dict class provides a method get() that accepts a key and a default value i.e. dict.get(key[, default]) Behavior of this function,
Let’s use get() function to check if given key exists in dictionary or not, # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'sample' # check if key exists in dictionary by checking if get() returned None if word_freq.get(key) is not None: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") Output: No, key: 'sample' does not exists in dictionary Here it confirmed that the key ‘sample’ does not exist in the dictionary. We passed ‘sample’ argument in the get() function, without any default value. As our dictionary does not contain ant key ‘sample’ and no default value is provided, therefore it returned None. If we pass the default value along with the key and if key does not exist in the dictionary, then it returns the default value. For example, key = 'sample' # check if key exists in dictionary by checking if get() returned default value if word_freq.get(key, -1) != -1: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") Output: No, key: 'sample' does not exists in dictionary Here it confirmed that the key ‘sample’ does not exist in the dictionary. We passed ‘sample’ argument in the get() function, along with the default value -1. As our dictionary does not contain ant key ‘sample’, so get() function returned the the default value. We cannot always be sure with the result of dict.get(), that key exists in dictionary or not . Therefore, we should use dict.get() to check existence of key in dictionary only if we are sure that there cannot be an entry of key with given default value. Python: check if key in dict using keys()keys() function of the dictionary returns a sequence of all keys in the dictionary. So, we can use ‘in’ keyword with the returned sequence of keys to check if key exist in the dictionary or not. For example, word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'test' if key in word_freq.keys(): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") Output: Yes, key: 'test' exists in dictionary Here it confirms that the key ‘test’ exist in the dictionary. python check if key in dictionary using try/exceptIf 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. def check_key_exist(test_dict, key): try: value = test_dict[key] return True except KeyError: return False # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'test' # check if dictionary has key in python if check_key_exist(word_freq, key): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") Output: Yes, key: 'test' exists in dictionary Here it confirms that the key ‘test’ exist in the dictionary. In function check_key_exist(), it access the value of given key. If key does not exist then KeyError occurs, in that case it returns False, otherwise it returns True Check if key not in dictionary in python using ‘if not in’ statementIn all the above example, we checked if key exist in dictionary or not. But if want to check if key doesn’t exist in dictionary then we can directly use ‘not in’ with dictionary i.e. word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'sample' # Check if key not in dict python if key not in word_freq: print(f"No, key: '{key}' does not exists in dictionary") else: print(f"Yes, key: '{key}' exists in dictionary") Output: No, key: 'sample' does not exists in dictionary Here it confirms that the key ‘test’ exist in the dictionary. Check if key exist in dictionary using has_key() functiondict provides a function has_key() to check if key exist in dictionary or not. But this function is discontinued in python 3. So, below example will run in python 2.7 only i.e. if word_freq.has_key('test'): print("Yes 'test' key exists in dict") else: print("No 'test' key does not exists in dict") Output: Yes, key: 'test' exists in dictionary Here it confirms that the key ‘test’ exist in the dictionary. The complete example is as follows. def check_key_exist(test_dict, key): try: value = test_dict[key] return True except KeyError: return False def main(): # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } print("*** Python: check if key in dictionary using if-in statement***") key = 'test' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") key = 'sample' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print("*** Python: check if dict has key using get() function ***") key = 'sample' # check if key exists in dictionary by checking if get() returned None if word_freq.get(key) is not None: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") key = 'sample' # check if key exists in dictionary by checking if get() returned default value if word_freq.get(key, -1) != -1: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print('python check if key in dict using keys()') key = 'test' if key in word_freq.keys(): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print('python check if key in dict using try/except') print('python check if key in dictionary using try/except') key = 'test' # check if dictionary has key in python if check_key_exist(word_freq, key): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print('check if key not in dictionary in python using if not in statement') key = 'sample' # Check if key not in dict python if key not in word_freq: print(f"No, key: '{key}' does not exists in dictionary") else: print(f"Yes, key: '{key}' exists in dictionary") print('check if key not in dictionary in python using has_keys') if __name__ == '__main__': main() Output *** Python: check if key in dictionary using if-in statement*** Yes, key: 'test' exists in dictionary No, key: 'sample' does not exists in dictionary *** Python: check if dict has key using get() function *** No, key: 'sample' does not exists in dictionary No, key: 'sample' does not exists in dictionary python check if key in dict using keys() Yes, key: 'test' exists in dictionary python check if key in dict using try/except python check if key in dictionary using try/except Yes, key: 'test' exists in dictionary check if key not in dictionary in python using if not in statement No, key: 'sample' does not exists in dictionary check if key not in dictionary in python using has_keys How do you check if a key does not exists in a dictionary python?Check If Key Exists using get()
Using the Inbuilt method get() method returns a list of available keys in the dictionary. With the Inbuilt method keys(), use the if statement to check if the key is present in the dictionary or not. If the key is present it will print “Present” Otherwise it will print “Not Present”.
How do you check if a key isn't in a dictionary?The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value. This is the intended and preferred approach by most developers. Under the hood, it uses the __contains__() function to check if a given key is in a dictionary or not.
What does the get () method return when a key is not found in the dictionary?get() method returns a default value if the key is missing. However, if the key is not found when you use dict[key] , KeyError exception is raised.
|