Popping and deleting from dictionaries
Often, you will want to remove keys and value from a dictionary. You can do so using the del
Python instruction. It's important to remember that del
will throw a KeyError
if the key you are trying to delete does not exist. You can not use it with the .get()
method to safely delete items; however, it can be used with try: catch:
.
If you want to save that deleted data into another variable for further processing, the .pop()
dictionary method will do just that. You can supply a default value for .pop()
much like you did for .get()
to safely deal with missing keys. It's also typical to use .pop()
instead of del
since it is a safe method.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Remove
"Madison Square Park"
fromsquirrels_by_park
and store it assquirrels_madison
. - Safely remove
"City Hall Park"
fromsquirrels_by_park
with a empty dictionary as the default and store it assquirrels_city_hall
. To do this, pass in an empty dictionary{}
as a second argument to.pop()
. - Delete
"Union Square Park"
fromsquirrels_by_park
. - Print
squirrels_by_park
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Remove "Madison Square Park" from squirrels_by_park
squirrels_madison = ____
# Safely remove "City Hall Park" from squirrels_by_park with an empty dictionary as the default
squirrels_city_hall = ____.____(____, ____)
# Delete "Union Square Park" from squirrels_by_park
____ ____[____]
# Print squirrels_by_park
print(squirrels_by_park)