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 Program to Compute all the Permutation of the String
Python String find()
Python List clear()
Python oct()
Python Program to Sort Words in Alphabetic Order
Python locals()
Python Program to Check If a String Is a Number (Float)
Python dir()
Python Custom Exceptions
Python Set isdisjoint()
Python Set intersection()
Python Program to Transpose a Matrix
Python String zfill()
Python Program to Convert Bytes to a String
Python sleep()
Python Program to Get the File Name From the File Path
Python Dictionary fromkeys()
Python Dictionary items()
Python String swapcase()
Python Program to Find the Factors of a Number
Python Program to Count the Number of Occurrence of a Character in String
Python Set discard()
Python Program to Generate a Random Number
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python __import__()
Python Program to Randomly Select an Element From the List
Intelligent Projects Using Python - Santanu Pattanayak
Python String strip()
Python Program to Merge Two Dictionaries
Node.js vs Python for Backend Development
Python Set intersection_update()
Python zip()