We can check if a dictionary key is empty by evaluating whether its value is equal to None or an empty string.
How to check if a key exists in a Python dictionary
Key takeaways:
Always check if a key exists to avoid
KeyErrorexceptions when accessing dictionary values.Methods to check key existence:
The
if-instatement: Direct and clear way to check if a key existsThe
has_key()method: Deprecated in Python 3; used in Python 2Exception handling: Use of try-except blocks for robust error handling
The
keys()method: Retrieves a list of keys and check withif-inThe
get()method: ReturnsNoneif key is absent, useful for conditional logicThe
setdefault()method: Checks for a key and sets a default value if the key does not existBest practices: Choose the method that fits your needs:
if-infor simplicity,get()for default values, andsetdefault()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:
- Using the
if-instatement - Using the
has_key()method - Using exception handling
- Using the
keys()method - Using the
get()method - Using the
dict.setdefault()method
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:
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_keymethod, 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 hereelse: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?
What is the difference between key exists, and value exists?
How do we check if a value exists in a list in Python?
Can we check for multiple keys at once?
How do we check if a key exists in a JavaScript dictionary?
Free Resources