Home » Python

Python Dictionary popitem() Method with Example

Python Dictionary popitem() Method: Here, we are going to learn how to remove a random item or last inserted item from the dictionary in Python?
Submitted by IncludeHelp, on November 26, 2019

Dictionary popitem() Method

popitem() method is used to remove random/last inserted item from the dictionary.

Before the Python version 3.7, it removes random item and from version 3.7, it removes last inserted item.

Syntax:

    dictionary_name.popitem()

Parameter(s):

  • 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:

# Python Dictionary popitem() Method with Example

# 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:

# Python Dictionary popitem() Method with Example

# 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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.