Python check if key is in dictionary

In this example, you will learn to check if a key is present in a dictionary.

To understand this example, you should have the knowledge of the following Python programming topics:

  • Python Dictionary

Using in keyword

my_dict = {1: 'a', 2: 'b', 3: 'c'} if 2 in my_dict: print("present")

Output

present

Using if statement and in keyword, you can check if a key is present in a dictionary.

In the above example, 2 is present in the dictionary as a key; therefore, the output is present.

You can use not in if you want to check if a key is not present in the dictionary.

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.

# Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 }

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

Python: check if key in dictionary using if-in statement

We can directly use the ‘in operator’ with the dictionary to check if a key exist in dictionary or nor. The expression,

key in dictionary

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() function

In 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,

  • If given key exists in the dictionary, then it returns the value associated with this key,
  • If given key does not exists in dictionary, then it returns the passed default value argument.
  • If given key does not exists in dictionary and Default value is also not provided, then it returns None.

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/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.

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’ statement

In 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() function

dict 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 is in a dictionary Python?

Check If Key Exists using has_key() method 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 see if a key is not in a dictionary Python?

Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.

How do you check if a key

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

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

Python: Check if a value exists in the dictionary (3 Ways).
Check if value exist in a dict using values() & if-in statement..
Check if a value exists in python dictionary using for loop..
Check if a value exists in a dictionary using any() and List comprehension..

Postingan terbaru

LIHAT SEMUA