A dictionary (dict
) in Python is an unordered data structure that uses a "key-value" format. Any value within the dictionary is accessed by explicitly referencing the key associated with the desired value. Attempting to access a non-existent key results in a program error.
To avoid such errors, it’s essential to check whether a key exists in a dictionary before trying to access its value. Python provides several built-in methods for this purpose, which we discuss in this tutorial.
In this guide, we use Python 3.10.12 running on Ubuntu 22.04.
The most common way to check if a key exists in a dictionary is by using the in operator in an if/else condition:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'name'
if some_key in some_dict:
print('The key "' + some_key + '" was found.')
else:
print('The key "' + some_key + '" was not found.')
Here, the in operator returns True
if the key is found and False
otherwise.
You can also use the in
operator with the list of dictionary keys obtained via the dict.keys()
method:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'name'
if some_key in some_dict.keys():
print('The key "' + some_key + '" was found.')
else:
print('The key "' + some_key + '" was not found.')
As you can see, the logic is identical to the previous example, except that the dict.keys()
method is used instead of the dictionary instance.
At first glance, this approach might seem redundant. However, in practical applications, there may be scenarios where you specifically need to work with the list of dictionary keys rather than the dictionary itself.
Using dict.keys()
, you can elegantly determine if a specified key exists in the dictionary.
You can check for the presence of a key in a dictionary by attempting to retrieve its value using the built-in dict.get()
method:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'salary'
some_value = some_dict.get(some_key) # Try to fetch the value for the key
# If the returned value is None, it indicates the key does not exist
if some_value is not None:
print('The key "' + some_key + '" was found, and its value is "' + str(some_value) + '".')
else:
print('The key "' + some_key + '" was not found.')
As shown, accessing a non-existent key with dict.get()
will not raise an error (as would happen with square bracket access) but will return a None
value.
However, this method has a potential drawback: the requested key might actually exist in the dictionary, but its value could still be None
:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...', 'salary': None}
some_key = 'salary' # The key exists, but its value is None
some_value = some_dict.get(some_key) # Returns None
print('It is unclear if the key "' + some_key + '" exists or if it exists with a value of None.')
In such cases, whether the key does not exist or exists with a None
value is ambiguous.
We can address this issue by using the ability of dict.get()
to set a default value for non-existent keys:
some_dict1 = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...', 'salary': None}
some_dict2 = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'salary'
some_value1 = some_dict1.get(some_key, "Salary not specified")
some_value2 = some_dict2.get(some_key, "Salary not specified")
print('Attempting to access the key "' + some_key + '" returned the value "' + str(some_value1) + '".')
print('Attempting to access the key "' + some_key + '" returned the value "' + str(some_value2) + '".')
Console output:
Attempting to access the key "salary" returned the value "None".
Attempting to access the key "salary" returned the value "Salary not specified".
If you attempt to retrieve the value of a non-existent key using square brackets, it will always result in an error. In the future, this error can be handled using a try/except
block, thereby determining whether the key actually exists.
You can check if a key exists in a dictionary by handling errors with try/except
—a direct, "straightforward" approach.
In this method, if accessing the key raises an error, it indicates that the key does not exist. Conversely, if no error is raised, the key exists.
To implement this, wrap the key access in a try/except block:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'name'
try:
some_value = some_dict[some_key]
print('The key "' + some_key + '" was found, and its value is "' + some_value + '".')
except KeyError:
print('The key "' + some_key + '" was not found.')
This method of checking for a key in a Python dictionary should generally be used as a fallback when other methods are not suitable.
This is because exception handling in Python tends to be relatively slow, which can reduce program performance. Nonetheless, checking a key via try/except
is a valid approach when needed.
In programs with more complex logic, explicit key searches in a dictionary might be required—especially if the search is combined with modifying the values of the found keys.
In such cases, you can manually iterate over the dictionary using a for
loop:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'name'
is_found = False # Variable to store the search status
# Iterate through the dictionary
for found_key in some_dict:
if found_key == some_key:
is_found = True
some_dict[found_key] = 'Jim' # Modify the value of the found key
if is_found:
print('The key "' + some_key + '" was found, and its value is now "' + some_dict[some_key] + '".')
else:
print('The key "' + some_key + '" was not found.')
In this example, all dictionary keys are sequentially iterated over, and the value of the found key is modified.
This approach allows for implementing more complex logic, combining both key searches and value modifications.
In some cases, it might be useful to use a while
loop instead of a for
loop:
some_dict = {'name': 'James', 'age': 35, 'occupation': 'Just a guy...'}
some_key = 'occupation'
is_found = False
some_keys = list(some_dict) # Convert dictionary keys to a list
i = 0
while i < len(some_keys):
if some_keys[i] == some_key:
is_found = True
some_dict[some_key] = 'Jim' # Modify the value of the found key
break
i += 1
if is_found:
print('The key "' + some_key + '" was found, and its value is now "' + some_dict[some_key] + '".')
else:
print('The key "' + some_key + '" was not found.')
While the overall application logic does not change, the syntax differs from the for
loop approach.
Before accessing a value in a dictionary, it is essential to ensure that the desired key exists in the dictionary. Otherwise, you may encounter an error, causing the program to crash.
This check can be performed using several built-in methods:
in
operatordict.get()
functiontry/except
exception handlingfor
and while
loopsEach specific scenario calls for a different method of checking. For the simplest cases, the in
operator is typically used. When the application logic is more complex and requires additional actions, a for
or while
loop may be employed.
If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.