Removes a key from the dictionary
Usage
If specified key is in the dictionary, the pop()
method removes it and returns its value. You can also specify the default parameter that will be returned if the specified key is not found.
If default is not specified and key is not in the dictionary, a KeyError is raised.
Syntax
dictionary.pop(key,default)
Parameter | Condition | Description |
key | Required | Any key you want to remove |
default | Optional | A value to return if the specified key is not found. |
Examples
pop()
method is generally used to remove a key from the dictionary.
D = {'name': 'Bob', 'age': 25}
D.pop('age')
print(D)
# Prints {'name': 'Bob'}
This method not only removes the specified key, but also returns its value.
D = {'name': 'Bob', 'age': 25}
v = D.pop('age')
print(v)
# Prints 25
If key is not in the dictionary, the method raises KeyError exception.
D = {'name': 'Bob', 'age': 25}
D.pop('job')
# Triggers KeyError: 'job'
To avoid such an exception, you need to specify the default parameter.
The default Parameter
If key is in the dictionary, the pop()
method removes it and returns its value
(no matter what you pass in as default).
D = {'name': 'Bob', 'age': 25}
v = D.pop('age', 0)
print(D)
# Prints {'name': 'Bob'}
print(v)
# Prints 25
But if key is not in the dictionary, the method returns specified default.
D = {'name': 'Bob', 'age': 25}
v = D.pop('job', 'Developer')
print(v)
# Prints Developer