Thanks to visit codestin.com
Credit goes to www.pythonmorsels.com

Removing a dictionary key PREMIUM

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
4 min. read 3 min. video Python 3.10—3.14
Python Morsels
Watch as video
02:54

Let's talk about removing items from a dictionary in Python.

Using Python's del statement

Here 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 function

Now, 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.

Using the dictionary pop method

The 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"]

Attempting to delete missing items

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'

Default values when deleting

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)

Use the del statement or pop method to delete dictionary items

Just 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.

Python Morsels
Watch as video
02:54
This is a free preview of a premium screencast. You have 2 previews remaining.