×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Dictionary pop() Method

By IncludeHelp Last updated : December 21, 2024

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'

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.