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 Directory and Files Management
Python List insert()
Python dir()
Python Program to Check Whether a String is Palindrome or Not
Python Global Keyword
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Package
Python Set add()
Python List extend()
Python Program to Find the Factors of a Number
Python Program to Check the File Size
Python Exception Handling Using try, except and finally statement
Python str()
Python Strings
Python while Loop
Python Program to Convert Kilometers to Miles
Python reversed()
Python Dictionary get()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Display Calendar
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Print all Prime Numbers in an Interval
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Display Powers of 2 Using Anonymous Function
Python __import__()
Python Program to Convert Bytes to a String
Python String rfind()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Sets
Python classmethod()
Python Program to Find the Square Root
Python Program to Find Armstrong Number in an Interval