Home »
Python
Python Dictionary pop() Method (with Examples)
Python Dictionary pop() Method: In this tutorial, we will learn about the pop() method of a dictionary with its usage, syntax, parameters, return type, and examples.
By IncludeHelp Last updated : June 12, 2023
Python Dictionary pop() Method
The pop() is an inbuilt method of dict class that is used to remove an item from the dictionary with specified key from the dictionary. The method is called with this dictionary and returns the type of the deleted value.
Syntax
The following is the syntax of pop() method:
dictionary_name.pop(key, value)
Parameter(s):
The following are the parameter(s):
- key – It represents the specified key whose value to be removed.
- value – It is an optional parameter, it is used to specify the value to be returned if "key" does not exist in the dictionary.
Return Value
The return type of this method is the type of the value, it returns the value which is being removed.
Note: If we do not specify the value and key does not exist in the dictionary, then method returns an error.
Example 1: Use of Dictionary pop() Method
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# removing 'roll_no'
x = student.pop('roll_no')
print(x, ' is removed.')
# removing 'name'
x = student.pop('name')
print(x, ' is removed.')
# removing 'course'
x = student.pop('course')
print(x, ' is removed.')
# removing 'perc'
x = student.pop('perc')
print(x, ' is removed.')
# printing default value if key does
# not exist
x = student.pop('address', 'address does not exist.')
print(x)
Output
data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
101 is removed.
Shivang is removed.
B.Tech is removed.
98.5 is removed.
address does not exist.
Demonstrate the example, if key does not exist and value is not specified.
Example 2: Use of Dictionary pop() Method
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# demonstrating, when method returns an error
# if key does not exist and value is not specified
student.pop('address')
Output
data of student dictionary...
{'course': 'B.Tech', 'name': 'Shivang', 'roll_no': 101, 'perc': 98.5}
Traceback (most recent call last):
File "main.py", line 17, in <module>
student.pop('address')
KeyError: 'address'