/  Technology   /  Check if a given key already exists in a dictionary
Datascience in car technology

Check if a given key already exists in a dictionary

Check if a given key already exists in a dictionary

 

Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets. Dictionaries are indexed by keys. They are generally optimized to retrieve values when the key is known. Values (definitions) are mapped to a specific key (words) similar to that of a dictionary in the real world. 

Now our task is to check if a given key exists in a dictionary or not. We can accomplish this through the ways below:

  • Using the keys() method
  • Using if and in
  • Using has_key()
  1. Using keys() method:

This inbuilt method returns a list of all the available keys in a given dictionary. We use this along with the ‘in’  keyword.

  1. Using if and in:

Here we won’t necessarily use the keys() method. It just returns a boolean value, True if present else returns False

  1. Using has_key():

This method also returns a boolean value, True if the key is present in the dictionary else False. We use this method along with the if statement as shown below. 

This method is no longer supported by the versions Python 3 and above. We can only use it in Python 2. The output is much similar to the above mentioned ways.

Leave a comment