How to check if a key exists in a Python dictionary?


A dictionary maintains mappings of unique keys to values in an unordered and mutable manner. In python, dictionaries are a unique data structure, and the data values are stored in key:value pairs using dictionaries. Dictionaries are written with curly brackets and have keys and values.

Dictionaries are now ordered as of Python 3.7. Dictionaries in Python 3.6 and before are not sorted.

Example

In the following example, companyname, and tagline are the keys, and Tutorialspoint, simplyeasylearning are the values respectively.

thisdict = { "companyname": "Tutorialspoint", "tagline" : "simplyeasylearning", } print(thisdict)

Output

The above code produces the following results

{'companyname': 'Tutorialspoint', 'tagline': 'simplyeasylearning'}

In this article, we check if a key is present in the dictionary or not. To do so, there are many methods and each of these are discussed below.

Using the in operator

We use the ‘in’ operator to check if the key is present in the dictionary.

The ‘in’ operator returns “True” if the key is present in the given dictionary and returns “False” if the key is not present in the dictionary.

Example 1

The following example, uses the in operator to check if a particular key is present in the given dictionary or not.

this_dict = { "companyname" : "Tutorialspoint", "tagline" : "simplyeasylearning" , 'location': 'India'} if "companyname" in this_dict: print("Exists") else: print("Does not exist") if "name" in this_dict: print("Exists") else: print("Does not exist")

Output

The output produced is shown below.

Exists
Does not exist

Example 2

Following is another example of this −

Example 2

Following is another example of this −

my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'} print('name' in my_dict) print('foo' in my_dict)

Output

This will give the output −

True
False

Using the get() method

In this method, we use the get() method to know if the key is present in the dictionary or not. The get() method returns the value of the item with the specified key.

Syntax

This is the syntax of the get() method in python.

dict.get(key,value)

Where,

  • key - The keyname of the object from which you want to retrieve the value.
  • value - If the given key does not exist, this value is returned. Default value is None.

Example 1

This example shows the usage of the get() method available in python.

this_dict = { "companyname" : "Tutorialspoint", "tagline" : "simplyeasylearning" , 'location': 'India'} if this_dict.get("tagline") is not None: print("Exists") else: print("Does not exist") if this_dict.get("address") is not None: print("Exists") else: print("Does not exist")

Output

The output produced when the above code is run, is shown below.

Exists
Does not exist

Updated on: 05-Sep-2022

918 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements