In this tutorial, you’ll learn how to safely remove keys from a Python dictionary. By safely, I mean that the code will not throw an error, should the key not actually exist in the dictionary. You’ll learn how to do this using the .pop()
method, the del
keyword, as well as dictionary comprehensions. Finally, you’ll learn how to delete multiple keys from a dictionary in Python. Let’s get started!
The Quick Answer: Use .pop()
to Remove Key from Python Dictionary
Table of Contents
What are Python Dictionaries?
Python dictionaries are built-in data structures that are used to store data in key:value pairs. Beginning in Python 3.7, dictionaries are ordered objects. They are also changeable and do not allow duplicate keys.
To create an empty dictionary, say a_dict
, you could write:
a_dict = dict()
# Or: a_dict = {}
Let’s create a new dictionary that we’ll use throughout this tutorial:
a_dict = {
'John': 32,
'Mel': 31,
'Nik': 33,
'Katie': 32,
'James': 29,
'Matt': 35
}
Now that you have an understanding of what dictionaries are, let’s see how we can use Python to remove a key from a dictionary.
Use Python .pop() to Delete a Key from a Dictionary
The Python .pop()
method is a very useful method that allows us to get a dictionary item and remove its key from the dictionary.
The Python .pop()
method works like this:
dictionary.pop(key, default_value)
The first parameter is the key we want to remove and the second (optional) parameter is the value that should be returned if the key doesn’t exist.
There are three outcomes to using the .pop()
method:
- The key exists in the dictionary, in which case, the key’s value is returned and the key is removed from the dictionary
- The key doesn’t exist and a default value is provided, in which case, the default value is returned.
- The key doesn’t exist and a default value is not provided, in which case, a
KeyError
is thrown
Let’s see how we can use the Python dictionary .pop()
method to remove a key from our dictionary:
# Delete a key using .pop()
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
a_dict.pop('John')
print(a_dict)
# Returns: {'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
Now, let’s see what happens when we try to remove a key that doesn’t exist:
# Delete a key that doesn't exist using .pop()
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
a_dict.pop('Jamie')
print(a_dict)
# Returns: KeyError: 'Jamie'
If we want to be able to safely remove a key from a dictionary, meaning that no error is returned, we can pass in a default value into our .pop()
method. A good default value would be to return None
, as it allows us to simply move on.
# Delete a key that doesn't exist using .pop()
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
a_dict.pop('Jamie', None)
print(a_dict)
# Returns: {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
We can see that using the .pop()
method allows us to safely remove a key from a Python dictionary. Now, let’s see how we can use the del
keyword to remove a key from a dictionary.
Use Python del to Remove a Key from a Dictionary
Python also provides the del
keyword to remove a key from a dictionary. Using the del
keyword is a less safe approach, as there is not way to simply provide a default_value
, as you can with the .pop()
method.
Let’s see how we can use Python to remove a key using the del
keyword:
# Delete a key using del
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
del a_dict['John']
print(a_dict)
# Returns: {'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
If we try to delete a key that doesn’t exist, Python will throw a KeyError
. Let’s see how this looks:
# Delete a key that doesn't exist using del
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
del a_dict['Mike']
print(a_dict)
# Returns: KeyError: 'Mike'
In order to not throw a KeyError
, we can use a try-except
statement. Let’s see how this looks:
# Safely remove a key from a dictionary using try-except
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
try:
del a_dict['Mike']
except KeyError:
pass
print(a_dict)
# Returns: {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
We can see while it’s possible to safely remove a key from a Python dictionary using the del
keyword, it may be better to simply just use the .pop()
method.
In the next section, you’ll learn how to remove a key from a Python dictionary using a dictionary comprehension.
Use a Python Dictionary Comprehension to Remove a Key from a Dictionary
Dictionary comprehensions are quick one-liners in Python that allow you to easily create dictionaries. It’s important to understand here that we’re creating a new dictionary, so it’s not the most memory-efficient method of deleting a key. However, if you’re sure a key exists and the dictionary isn’t too large, this is one way to easily remove a key from a Python dictionary.
Want to learn more? Check out my in-depth tutorial on how Python dictionary comprehensions work.
See the graphic below to see how Python dictionary comprehensions work:
Now that you have an understanding of how Python dictionary comprehensions work, let’s see how you can use them to delete a key from a dictionary:
# Delete a Key using a Dictionary Comprehension
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
a_dict = {key:a_dict[key] for key in a_dict if key != 'John'}
print(a_dict)
# Returns: {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
Because the comprehension uses an if
statement, we can say that this is a safe method of deleting a key from a Python dictionary.
How to Remove Multiple Keys from a Python Dictionary
Python makes it easy to remove multiple keys from a dictionary. The safest way of doing this is to loop over a list of keys and use the .pop()
method.
Let’s see how we can pass in a list of different keys to delete, including some that don’t exist:
# How to remove multiple keys from a Python dictionary
a_dict = {'John': 32, 'Mel': 31, 'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
keys = ['John', 'Mary', 'Mel']
for key in keys:
a_dict.pop(key, None)
print(a_dict)
# Returns: {'Nik': 33, 'Katie': 32, 'James': 29, 'Matt': 35}
Take note that we pass in None
as the default_value, in order to make sure that no KeyError
is thrown when a key doesn’t exist.
Conclusion
In this post, you learned how to safely remove keys from a Python dictionary. You learned how to do this using the .pop()
method, the del
keyword, and using a dictionary compreghension. Finally, you learned how to safely remove multiple keys from a Python dictionary.
To learn more about the Python dictionary .pop()
method, check out the official documentation here.
Pingback: Python: Check if a Dictionary is Empty (5 Ways!) • datagy
Re: ‘Use a Python Dictionary Comprehension to Remove a Key from a Dictionary’ :
The resulting dictionary should have eliminated the key/value pair ‘John’: 32′, but did not.