How to check if a key exists in a Python dictionary

Key takeaways:

  • Always check if a key exists to avoid KeyError exceptions when accessing dictionary values.

  • Methods to check key existence:

    • The if-in statement: Direct and clear way to check if a key exists

    • The has_key() method: Deprecated in Python 3; used in Python 2

    • Exception handling: Use of try-except blocks for robust error handling

    • The keys() method: Retrieves a list of keys and check with if-in

    • The get() method: Returns None if key is absent, useful for conditional logic

    • The setdefault() method: Checks for a key and sets a default value if the key does not exist

  • Best practices: Choose the method that fits your needs: if-in for simplicity, get() for default values, and setdefault() for setting defaults.

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

Note: When we index a dictionary with a key that does not exist, it throws an error.

Therefore, it’s a safe practice to check if the key exists in the dictionary before extracting the key value. Also, checking the keys will help us not to insert duplicate key values.

Explicitly checking if a key exists in a dictionary is both a beautiful and simple approach—reducing complexity and preventing errors.

Methods to check for the presence of a key in a Python dictionary

Python offers multiple ways to check if the key exists in the dictionary, as listed below:

Method 1: Check if the key exists using the if-in statement

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

Syntax

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

Code example

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"

Method 2: Check if the key exists using the has_key() method

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

Syntax

Here’s the syntax of the has_key() method:

svg viewer

Code example

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.

Method 3: Check if the key exists using exception handling

Exception handling includes the try-except block to first check if the key exists. Otherwise, it handles the KeyError exception.

Syntax

Here’s the syntax to check if the key exists using exception handling:

try:
# check key: dict["key"]
print "The key exists in the dictionary"
except KeyError as error:
print "Key does not exist"

Code example

The code below illustrates the usage of the exception handling:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
try:
Fruits["b"]
print "The key exists in the dictionary"
except KeyError as error:
print "Key does not exist"

Method 4: Check if the key exists using keys() method

The built-in keys() method in Python is used to return a view object that contains all the keys of a dictionary in a list. To check if the key exists, we use keys() method with if-in statement.

Syntax

The following is the syntax to check if the key exists using the keys() method:

if key in dict.keys():
# add logic here
else:
print "Key does not exist"

Code example

The code below illustrates the usage of the keys() method:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
key = 'a'
if key in Fruits.keys():
print "The key exists in the dictionary"
else:
print "Key does not exist"

Method 5: Check if the key exists using the get() method

The get() method is used to get the value of the specified key. If the key exists, it returns a value, otherwise it returns None.

Syntax

The following syntax is used to check if the key exists using the get() method:

if dict.get('key') == None:
print "The key exists in the dictionary"
else:
print "Key does not exist"

Code example

The code below illustrates the usage of the get() method:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
if Fruits.get('b') == None:
print "Key does not exist"
else:
print "The key exists in the dictionary"

Method 6: Check if the key exists using the dict.setdefault() method

The built-in setdefault() method in Python is used to return the value of a key in a dictionary. This method allows us to insert the key with a specified default value if the key doesn’t exist.

Syntax

The following syntax is used to check if the key exists using the dict.setdefault() method:

dict.setdefault(key, value)

Here, value is an optional parameter, which becomes the value of the key. If not provided and the key does not exist, it will assign None to the given key.

Code example

The code below illustrates the usage of the setdefault() method:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
if Fruits.setdefault('b'):
print "The key exists in the dictionary"
print(Fruits)

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do we check if a dictionary key is empty in Python?

We can check if a dictionary key is empty by evaluating whether its value is equal to None or an empty string.


What is the difference between key exists, and value exists?

If a value exists in the dictionary, it means there’s at least one key with that specific value; if a key exists in the dictionary, it means it exists in the dictionary.


How do we check if a value exists in a list in Python?

We can check if a value exists in a list in Python using multiple methods, as listed below:


Can we check for multiple keys at once?

Yes, we can check for multiple keys at once by using a loop combined with the in operator to verify the existence of each key.


How do we check if a key exists in a JavaScript dictionary?

We can check if a key exists in a JavaScript dictionary using the in operator.

let Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
let key = 'b';

if (key in Fruits) {
    console.log('Key exists.');
} else {
    console.log('Key does not exist.');
}

Copyright ©2024 Educative, Inc. All rights reserved