Sign in to your Python Morsels account to save your screencast settings.
Don't have an account yet? Sign up here.
Let's talk about removing items from a dictionary in Python.
del statementHere we have a dictionary called rooms:
>>> rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
You can look up a value for a key in a dictionary by using the square bracket syntax ([]), often called subscripting:
>>> rooms["Pink"]
'Room 403'
You can also assign a key-value pair by using the same syntax within an assignment statement:
>>> rooms["Pink"] = "Room 307"
>>> rooms["Pink"]
'Room 307'
This square bracket syntax can also be used with Python's del statement to remove items from a dictionary:
>>> rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
>>> del rooms["Pink"]
>>> rooms
{'Ocean': 'Room 205', 'Space': 'Room 201'}
The del statement deletes a key value-pair from a dictionary.
This isn't the only use of del, but it is the most common use of Python's del statement.
del is statement, not a functionNow, note that I'm saying "the del statement", and not "the del function".
While you can put parentheses around del, they don't actually do anything:
>>> rooms
{'Ocean': 'Room 205', 'Space': 'Room 201'}
>>> del(rooms["Ocean"])
In fact, they'd probably mislead the person reading this line of code into thinking that del is a function.
But it's not, it's a statement.
While functions can be embedded within a larger line of code, statements can't be:
>>> print(del rooms["Space"])
File "<stdin>", line 1
print(del rooms["Space"])
^^^
SyntaxError: invalid syntax
Just like the return statement, the del statement must stand on its own.
pop methodThe del statement isn't the only way to delete an item from a dictionary: dictionaries also have a pop method.
The pop method accepts a key and deletes that key from the dictionary, while also returning the value for that key.
>>> rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
>>> rooms.pop("Pink")
'Room 403'
>>> rooms
{'Ocean': 'Room 205', 'Space': 'Room 201'}
If we wanted to get the value for a key before we delete it from our dictionary, we could use a key lookup and an assignment statement to store that key and then use the del statement to remove the key:
rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
space_room = rooms["Space"]
del rooms["Space"]
print("Space room used to be in", space_room)
Or we could just use the pop method:
rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
space_room = rooms.pop("Space")
print("Space room used to be in", space_room)
You can think of the pop method:
space_room = rooms.pop("Space")
As basically a shortcut for those two lines of code:
space_room = rooms["Space"]
del rooms["Space"]
What would happen if we tried to delete a key that isn't in our dictionary?
>>> rooms = {"Pink": "Room 403", "Ocean": "Room 205", "Space": "Room 201"}
>>> del rooms["Garden"]
If we try to use the del statement to delete a key that doesn't actually exist in our dictionary, we'll see a KeyError exception raised:
>>> del rooms["Garden"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Garden'
The same thing would happen if we used the pop method to delete a key that doesn't exist.
>>> rooms.pop("Garden")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Garden'
In fact, even if we try to look up a key that isn't in our dictionary, we'll see a KeyError exception:
>>> rooms["Garden"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Garden'
The pop method actually accepts an optional second argument, which acts as a default value if it's given.
>>> rooms.pop("Garden", "Not Found")
So if that key isn't in our dictionary, we'll get that default value instead of seeing a KeyError exception:
>>> rooms.pop("Garden", "Not Found")
'Not Found'
If we wanted to delete a key from our dictionary while getting the original value or getting a default value if the key wasn't in our dictionary, we could use an if statement to check if it's in our dictionary and then use a key lookup and the del statement:
session = {"authenticated": True}
if "source" in session:
source = session["source"]
del session["source"]
else:
source = None
Or we could just use the pop method to do all of that work for us:
session = {"authenticated": True}
source = session.pop("source", None)
del statement or pop method to delete dictionary itemsJust as we can look up dictionary items by their keys, we can also delete dictionary items based on their keys.
To delete a key from a dictionary, you can use Python's del statement or you can use the dictionary pop method.
Sign up for my free 5 day email course and learn essential concepts that introductory courses often overlook: iterables, callables, pointers, duck typing, and namespaces.
Sign in to your Python Morsels account to track your progress.
Don't have an account yet? Sign up here.
Sign up for my free 5 day email course and learn essential concepts that introductory courses often overlook: iterables, callables, pointers, duck typing, and namespaces. Learn to avoid beginner pitfalls, in less than a week!
Ready to level up? Sign up now to begin your Python journey the right way!