Python Dictionary popitem() Method (with Examples)

Python Dictionary popitem() Method: In this tutorial, we will learn about the popitem() method of a dictionary with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 12, 2023

Python Dictionary popitem() Method

The popitem() is an inbuilt method of dict class that is used to remove random/last inserted item from the dictionary. Before Python version 3.7, it removes the random item and from version 3.7, it removes the last inserted item. The method is called with this dictionary and returns the removed item as a tuple (key, value).

Syntax

The following is the syntax of popitem() method:

dictionary_name.popitem()

Parameter(s):

The following are the parameter(s):

  • None - It does not accept any parameter.

Return Value

The return type of this method is <class 'tuple'>, it returns the removed item as a tuple (key, value).

Example 1: Use of Dictionary popitem() 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 item
x = student.popitem()
print(x, ' is removed.')

# removing item
x = student.popitem()
print(x, ' is removed.')

Output (On Python version 3)

data of student dictionary...
{'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'roll_no': 101}
('name', 'Shivang')  is removed.
('course', 'B.Tech')  is removed.

Output (On Python version 3.7.4)

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
('perc', 98.5)  is removed.
('course', 'B.Tech')  is removed.

Demonstrate the example, if no more item exists then it returns an error.

Example 2: Use of Dictionary popitem() Method

# dictionary declaration
temp = {
  "key1": 1,
  "key2": 2
}

# printing dictionary
print("data of temp dictionary...")
print(temp)

# popping item
x = temp.popitem()
print(x, 'is removed.')

# popping item
x = temp.popitem()
print(x, 'is removed.')

# popping item
x = temp.popitem()
print(x, 'is removed.')

Output

data of temp dictionary...
{'key2': 2, 'key1': 1}
('key2', 2) is removed.
('key1', 1) is removed.
Traceback (most recent call last):
  File "main.py", line 22, in <module>
    x = temp.popitem()
KeyError: 'popitem(): dictionary is empty'

Comments and Discussions!

Load comments ↻






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