Trusted answers to developer questions

How to check if a key exists in a Python dictionary

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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:

  • if-in statement
  • has_key()

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:

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"

has_key method

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"

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

RELATED TAGS

python
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?