Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dictionary
key
check
exists
python

How to check if a key exists in a Python dictionary

Educative Answers Team

NOTE: The method referred to in this shot, the Python has_key method, has deprecated and is not available in Python 3.

A dictionary is a valuable data structure in Python; it holds key-value pairs. During programming, there is often a need to extract the value of a given key from a dictionary; however, it is not always guaranteed that a specific key exists in the dictionary.

When you index a dictionary with a key that does not exist, it will throw an error.

Hence, it is a safe practice to check whether or not the key exists in the dictionary prior to extracting the value of that key. For that purpose, Python offers two built-in functions:

  • has_key()

  • if-in statement

svg viewer

1. has_key

The has_key method returns true if a given key is available in the dictionary; otherwise, it returns false.

Syntax

See the syntax of the has_key method below:

svg viewer

Code

The code snippet below illustrates the usage of the has_key method:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
key_to_lookup = 'a'
if Fruits.has_key(key_to_lookup):
  print "Key exists"
else:
  print "Key does not exist"

The has_key method has been removed from Python3.

2. if-in statement

This approach uses the if-in statement to check whether or not a given key exists in the dictionary.

Syntax

The syntax below is used to look up a given key in the dictionary using​ an if-in statement:

svg viewer

Code

The code snippet below illustrates the usage of the if-in statement to check for the existence of a key in a dictionary:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
key_to_lookup = 'a'
if key_to_lookup in Fruits:
  print "Key exists"
else:
  print "Key does not exist"

RELATED TAGS

dictionary
key
check
exists
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses