Table of Contents
The Python popitem() method removes and returns the last element (key, value) pair inserted into the dictionary.
The syntax of popitem() is:
dict.popitem()
1. Parameters for popitem() method
The popitem() doesn’t take any parameters.
2. Return Value from popitem() method
The popitem() method removes and returns the (key, value) pair from the dictionary in the Last In, First Out (LIFO) order.
- Returns the latest inserted element (key,value) pair from the dictionary.
- Removes the returned element pair from the dictionary.
Note: Before Python 3.7, the popitem() method returned and removed an arbitrary element (key, value) pair from the dictionary.
3. Example: Working of popitem() method
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
# ('salary', 3500.0) is inserted at the last, so it is removed.
result = person.popitem()
print('Return Value = ', result)
print('person = ', person)
# inserting a new element pair
person['profession'] = 'Plumber'
# now ('profession', 'Plumber') is the latest element
result = person.popitem()
print('Return Value = ', result)
print('person = ', person)
Output
Return Value = ('salary', 3500.0)
person = {'name': 'Phill', 'age': 22}
Return Value = ('profession', 'Plumber')
person = {'name': 'Phill', 'age': 22}
Note: The
popitem()method raises aKeyErrorerror if the dictionary is empty.
Related posts:
Python Data Structures and Algorithms - Benjamin Baka
Python bytes()
Python Package
Python String expandtabs()
Python Program to Get the Last Element of the List
Python min()
Python Program to Create a Long Multiline String
Python Dictionary clear()
Python Set union()
Python ord()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Parse a String to a Float or Int
Python Program to Capitalize the First Character of a String
Python Dictionary copy()
Python String capitalize()
Python map()
Python hasattr()
Python Machine Learning Eqution Reference - Sebastian Raschka
Machine Learning with Python for everyone - Mark E.Fenner
Deep Learning with Python - Francois Chollet
Python len()
Python Program to Find ASCII Value of Character
Python Program to Safely Create a Nested Directory
Python super()
Python while Loop
Python Program to Shuffle Deck of Cards
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Machine Learning - Sebastian Raschka
Python iter()
Python open()