The Python pop() method and del keyword remove keys from a dictionary. pop() accepts the name of the key you want to remove from the dictionary as an argument. The del keyword stands on its own and refers to a specific key.
Dictionaries are mutable objects. This means you can change the values dictionaries store. As a result, you can remove keys from dictionaries at any time if they are no longer needed.
Suppose you have a Python dictionary that stores information about books sold in a bookstore. You may decide to remove a key that denotes if the book has been on the manager’s recommended list.
Python Remove Key from Dictionary
To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.
In this guide, we discuss how to remove a key from a Python dictionary. We’ll walk through two examples so you can start removing dictionary keys quickly.
Remove Key from a Dictionary Python: pop()
The Python pop() method removes an item from a dictionary.
This method can also be used to remove items from a list at a particular index value. For this guide, we’ll focus on removing an item from a dictionary. Read our tutorial on the Python list pop() guide for more information on how to remove an item from a list.
The syntax for this method is:
dictionary.pop(key_to_remove, not_found)
The pop() method can accept either one or two parameters:
- The name of the key you want to remove (mandatory).
- The value that should be returned if a key cannot be found (optional).
By default, pop() returns the value associated with the key that removed from a dictionary.
If you only specify one parameter, the interpreter may throw a Python KeyError. This will happen if you try to remove an element from a dictionary that does not exist.
pop() Example
We’re building a program that keeps track of the shoes that are in stock at a local shoe store. Let’s start by defining a Python array. This array contains a list of shoes with which we can work:
shoes = [ { "id": 1, "name": "Air Force 1 Mid Casual", "brand": "Nike", "in_stock": True }, { "id": 2, "name": "Blazer Mid '77 Casual", "brand": "Nike", "in_stock": True }, { "id": 3, "name": "One Take Basketball Shoes", "brand": "Jordan", "in_stock": False } ]
Our list of shoes contains three dictionaries. Each dictionary contains four keys: id, name, brand, and in_stock. id is a unique identifier for a shoe. name is the name of a shoe. brand is the brand that manufactures a shoe. in_stock represents whether a shoe is in stock.
The shoe store has decided to remove the “in_stock” key. They want to replace the key with a new value that tracks how many pairs of each shoe are in stock. To remove the “in_stock” key from our dictionaries, we’re going to use the pop() method:
for s in shoes: remove_key = s.pop("in_stock", None) if remove_key != None: print("in_stock has been removed for the {} shoe.".format(s["name"])) else: print("No key has been removed for the {} shoe.".format(s["name"])) print(shoes)
The first parameter in the built-in function pop() is the name of the key we want to remove. Our code returns the second value if the specified key does not exist. By default, the pop() method returns the name of the removed key.
In each iteration of our loop, we check if the “in_stock” key has been removed using an Python if statement. If “remove_key” has a value other than None, it means our key is removed.
After we remove the “in_stock” key our dictionaries, our code prints our new dictionary to the console. Run our code and see what happens:
in_stock has been removed for the Air Force 1 Mid Casual shoe. in_stock has been removed for the Blazer Mid '77 Casual shoe. in_stock has been removed for the One Take Basketball Shoes shoe. [{'id': 1, 'name': 'Air Force 1 Mid Casual', 'brand': 'Nike'}, {'id': 2, 'name': "Blazer Mid '77 Casual", 'brand': 'Nike'}, {'id': 3, 'name': 'One Take Basketball Shoes', 'brand': 'Jordan'}]
We remove the “in_stock” for all our shoes. Our code shows us that our keys are removed and prints out our updated dictionary to the console.
Remove Key from a Dictionary Python: del
The Python del statement deletes an object. Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword.
The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary.
Let’s take a look at the syntax for this keyword:
del dictionary["key"]
We use the indexing notation to retrieve the item from the dictionary we want to remove. “key” represents the name of the key whose key-value pair we want to remove from the dictionary.
del Example
We’re going to build a program that removes a key from an individual dictionary. This dictionary contains detailed information about a particular shoe:
shoe = { "id": 3, "name": "One Take Basketball Shoes", "brand": "Jordan", "in_stock": False, "price": 100.00, "colors": ["Gray"], "discount": False }
The shoe store has decided they are not going to discount any Jordan shoes. They want to remove the “discount” key from the dictionary. We can do this using the del keyword:
del shoe["discount"] print(shoe)
This code deletes the “discount” key from our list and shows us the new dictionary:
{'id': 3, 'name': 'One Take Basketball Shoes', 'brand': 'Jordan', 'in_stock': False, 'price': 100.0, 'colors': ['Gray']}
The key “discount” is no longer in our dictionary.
Python pop() vs del
There are two differences between pop() and del.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
First, the pop() method returns the value of the key removed from a dictionary whereas del does not return any value.
Second, the del keyword returns a KeyError if a key is not in a dictionary. On the other hand, the pop() method only returns a KeyError if you do not specify a second parameter. The second parameter is the default value to be returned if a key is not present in a dictionary.
Conclusion
Both the pop() method and the del keyword let you remove keys from a dictionary. The pop() method is generally more useful because it is capable of returning a default value if a key is not deleted. This is handy as it helps prevent KeyErrors.
Do you want to learn more about coding in Python? Read our How to Learn Python guide. This guide contains a list of top online courses and learning resources you can use to build your knowledge of Python.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.