Python Dictionary pop() method
Python Dictionary pop() method
The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key.
Syntax
dictionary.pop(key[, default])
Parameter
key – This argument signifies the key which is to be searched for removal.
default – This parameter represents the value which is to be returned when the key is not in the dictionary.
Return
This method removes and returns an element from a dictionary if the key is found else a KeyError exception is raised if the key if not found and the default argument is not specified.
Example 1
# Python program explaining
# the dictionary.pop() method
# initialising the dictionary
fruits = {
"banana" : "apple",
"orange": "mango",
"grapes": 5
}
# printing the Dictionary
print("Dictionary:",fruits)
# removing the "banana" element from the dictionary.
leftFruit=fruits.pop("banana")
print("My final lists of fruits are\n", fruits)
Output
Dictionary: {'banana': 'apple', 'grapes': 5, 'orange': 'mango'}
My final lists of fruits are
{'grapes': 5, 'orange': 'mango'}
Example 2
# Python program explaining
# the dictionary.pop() method
# initializing dictionary
dictionary = { "Saturday" : 6, "Friday" : 5, "Monday" : 1,"Tuesday": 2 }
# Printing the specified dictionary
print ("The dictionary before deletion : " + str(dictionary))
# using pop to return and remove key-value pair
# provided default
popValue = dictionary.pop('Friday', 5)
# Printing the value co-linked with the specified popped key
print ("Value linked with poppped key is : " + str(popValue))
# using pop to return and remove key-value pair
# not provided default
popValue = dictionary.pop('Friday')
# Printing the value associated to popped key
# KeyError
print ("Value linked to poppped key is : " + str(popValue))
Output
The dictionary before deletion : {'Tuesday': 2, 'Monday': 1, 'Saturday': 6, 'Friday': 5}
Value linked with poppped key is : 5
Traceback (most recent call last):
File "main.py", line 19, in <module>
popValue = dictionary.pop('Friday')
KeyError: 'Friday'
Example 3
# Python program explaining
# the dictionary.pop() method
# initializing the fruits dictionary
fruits = { 'apple': 2, 'orange': 3, 'grapes': 4 }
# Poping an element that is not present from the dictionary, provided a default value
popList = fruits.pop('pineapple', 'strawberry')
print('The popped element is:', popList)
print('The dictionary is:', fruits)
Output
The popped element is: strawberry
The dictionary is: {'grapes': 4, 'apple': 2, 'orange': 3}
