Multiple ways to check key exists or not in Python with examples

There are multiple for loops in Python to iterate the Key and values of the dictionary.

Dictionary in Python contains key and value pairs. Dictionaries are created with and initialized with braces ({}) and pairs of objects are separated by commas.

emp = {'id': 1, 'name': 'john', 'salary': 3000}

This tutorial shows you multiple ways to check for keys found in Dictionary. The first way is using the in operator that returns True or False, the Second way is using the has_key method, and the third way is using try except to hand key exists or not.

How to Check key exists in a Dictionary in python

There are multiple ways we can check key exists in Dictionary

  • in operator

The in operator is used to check key exists in Dictionary. Returns True or False values.

It is useful in conditional expressions.

Syntax

keystring in dictionary

Here is an example

emp = {'id': 1, 'name': 'john', 'salary': 3000}

print("id" in emp)
print("id1" in emp)

if "id" in emp:
print("id exists in dictionary")
  • has_key method has_key is a method in the Dictionary class of Python 2. x version. This is removed in Python3.x version

key contains each iterated object key value that can be retrieved using the dictionary[key] syntax. It is also used as a boolean expression in Conditional Statements.

Here is an example

emp = {'id': 1, 'name': 'john', 'salary': 3000}
print(emp.has_key("id"))
print(emp.has_key("id1"))

if dict.has_key('id1')==1:
    print("id1 exists")
else:
    print("id1 not exists")

Output:

1
0
id1 not exists
  • try except#

Here is a syntax dictionary[key] is used in try and except, if the key exists.

if the key not exists, except the block is called with KeyError binding

try:
dictionary[key] # called if key exists
except KeyError: # called if key not exists
else: # called if key exists

Here is an example

emp = {'id': 1, 'name': 'john', 'salary': 3000}

# Check for key exists

try:
result=emp["id"]
print("exist",result)
except KeyError:
print("not")

# Check for key exists

try:
result=emp["id1"]
print("exist",result)
except KeyError:
print("not")

Output:

exist 1
not

Conclusion

Learned multiple ways to get keys in Dictionary.

  • in operator: fastest compared to all other approaches, Complexity is O(1)
  • has_key method in python2
  • try and except