dict.pop()

Removes a key from a dictionary and returns its value, optionally with a fallback value.

Returns
The value of the removed key, or default.
Changes the original
Yes
On this page

Example

#
Python
user = {"name": "Jack", "email": "jack@example.com", "token": "a1b2c3"}

token = user.pop("token")
print(token)
print(user)
print(user.pop("token", "none"))
Resultsaved result, you can check it
a1b2c3
{'name': 'Jack', 'email': 'jack@example.com'}
none

Definition and usage

#

The pop(key) method removes an entry from the dictionary and returns the value that was stored under that key. It comes in handy when you want to take data out and get rid of it at the same time, for example moving a field to another structure or stripping it before sending data onward.

When the key is missing, pop() raises KeyError. If you pass a second argument, it is returned instead of the error, and the dictionary stays unchanged. Writing data.pop("tmp", None) is a safe way to remove a key that might not exist.

Related tools are the del dict[key] statement, which removes an entry without returning the value, and the popitem() method, which removes and returns the most recently added pair.

Syntax

#
Syntax
dict.pop(key)
dict.pop(key, default)

Parameters

#
  • key

    a dictionary key

    The key to remove.
  • default

    optional

    The value returned when the key is missing. Without it, a missing key raises KeyError.

More examples

#
Missing key without a fallback value
Python
cart = {"HTML": 49}

try:
    cart.pop("Python")
except KeyError as error:
    print("KeyError:", error)
Resultsaved result, you can check it
KeyError: 'Python'
popitem() and del
Python
queue = {"task_1": "HTML", "task_2": "CSS", "task_3": "Python"}

print(queue.popitem())
del queue["task_1"]
print(queue)
Resultsaved result, you can check it
('task_3', 'Python')
{'task_2': 'CSS'}

Good practices

#
  • Remove a key that might not exist with pop(key, None). Then you need neither a condition nor a try block.
  • When you don't need the value of the removed key, del dict[key] is the shorter way to write it.

Related entries

#

Spotted a mistake or missing an example? Write to us.