Python Dictionary pop()

The dict.pop() method removes the key and returns its value. If a key does not exist in the dictionary, then returns the default value if specified, else throws a KeyError.

Syntax:

dict.pop(key, default)

Parameters:

  1. Key: The key to be removed from the dictionary.
  2. default: (Optional) The value to be returned if the key is not found in the dictionary.

Return Value:

Returns the value associated with the key. If a key is not found, then it returns the default value if the default parameter is specified. If the key is not found and the default parameter is not specified, then throws a KeyError.

The following example demonstrates the dict.pop() method.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
deletedValue = romanNums.pop('V')
print("The popped element is: ", deletedValue)
print("Updated dictionary: ",romanNums)

deletedValue = romanNums.pop('IV')
print("The popped element is: ", deletedValue)
print("Updated dictionary: ", romanNums)
Output
The popped element is:  5
Updated dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4}
The popped element is:  4
Updated dictionary:  {'I': 1, 'II': 2, 'III': 3}

If the key is not found and the default parameter is not specified, a KeyError is raised.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
deletedValue = romanNums.pop('VI')
print("The popped element is: ",deletedValue)
Output
KeyError: 'VI'

If the key is not found and the default parameter is specified, The default value will be returned.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
deletedValue = romanNums.pop('VI', 'Not Found')
print("The popped element is: ",deletedValue)
print("Updated dictionary: ",romanNums)
Output
The popped element is: Not Found
Updated dictionary:  {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}