The pop() function in python helps to remove and return a specified key element from the dictionary. The return value of this method should be the value of the removed item.
dictionary.pop(key[, default]) #where key which is to be searched
The pop() function takes two parameters. Python also supports list pop, which removes the specified index element from the list. If an index is not provided, the last element will be removed.
Parameter | Description | Required / Optional |
---|---|---|
key | The key name of the item you want to remove | Required |
default | A value to be return if the specified key does not exist. | Optional |
The return value of the pop() depends on the arguments given.
Input | Return Value |
---|---|
key exists | removed/popped element from the dictionary |
key not exist | default value |
key not exist & default value not given | KeyError exception |
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key = fruits.pop('mango')
print('The popped item is:', key)
print('The dictionary is:', fruits)
Output:
The popped item is: 5 The dictionary is: {'banana': 4, 'strawberry': 3}
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key= fruits.pop('orange')
Output:
KeyError: 'orange'
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key = fruits.pop('orange', 'grapes')
print('The popped item is:', key)
print('The dictionary is:', fruits)
Output:
The popped item is: grapes The dictionary is: { 'banana': 4,'mango': 5,'strawberry': 3