Python Dictionary pop() Method

Removes a key from the dictionary

Usage

If specified key is in the dictionary, the pop() method removes it and returns its value, else returns default.

If default is not specified and key is not in the dictionary, a KeyError is raised.

Syntax

dictionary.pop(key,default)

Python dictionary pop() method parameters
ParameterConditionDescription
keyRequiredAny key you want to remove
defaultOptionalA value to return if the specified key is not found.

Basic Example

pop() method is generally used to remove a key from the dictionary.

Example: Remove ‘age’ from the dictionary

D = {'name': 'Bob', 'age': 25}
D.pop('age')
print(D)    # {'name': 'Bob'}

pop() Method Scenarios

The method’s output depends on input parameters. Here are three scenarios for different input parameters.

Key Present

If key is in the dictionary, the pop() method removes it and returns its value
 (no matter what you pass in as default).

Example:

D = {'name': 'Bob', 'age': 25}
v = D.pop('age')
print(D)    # {'name': 'Bob'}
print(v)    # 25

Default value is ignored if key is present

D = {'name': 'Bob', 'age': 25}
v = D.pop('age', 0)
print(D)    # {'name': 'Bob'}
print(v)    # 25

Key Absent, Default Specified

If key is not in the dictionary, the method returns specified default.

Example:

D = {'name': 'Bob', 'age': 25}
v = D.pop('job', 'Developer')
print(v)    # Developer

Key Absent, Default Not Specified

If key is not in the dictionary and default is not specified, the method raises KeyError exception.

Example:

# KeyError: 'job'
D = {'name': 'Bob', 'age': 25}
D.pop('job')