English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The pop() method deletes the dictionary given key key and the corresponding value, and returns the value to be deleted. The key value must be given. Otherwise, return the default value.
The syntax of the pop() method is
dictionary.pop(key[, default])
The pop() method takes two parameters:
key -The key to be deleted
default -When the key is not in the dictionary, the returned value will be
The pop() method returns:
If the key is found-Remove from the dictionary/Popped element
If the key is not found-Specify the value as the second parameter (default value)
If the key is not found and no default parameter is specified- Trigger KeyError exception
# Random sales dictionary sales = {'apple': 2, 'orange': 3, 'grapes': 4 } element = sales.pop('apple') print('The popped element is:', element) print('The dictionary is:', sales)
When running the program, the output is:
The popped element is: 2 The dictionary is: {'orange': 3, 'grapes': 4}
# Random sales dictionary sales = {'apple': 2, 'orange': 3, 'grapes': 4 } element = sales.pop('guava')
When running the program, the output is:
KeyError: 'guava'
# Random sales dictionary sales = {'apple': 2, 'orange': 3, 'grapes': 4 } element = sales.pop('guava', 'banana') print('The popped element is:', element) print('The dictionary is:', sales)
When running the program, the output is:
The popped element is: banana The dictionary is: {'apple': 2, 'orange': 3, 'grapes': 4}