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 input()
Python Program to Get the Last Element of the List
Python Program to Remove Duplicate Element From a List
Python Dictionary setdefault()
Python File I/O Operation
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Print Output Without a Newline
Python Program to Find HCF or GCD
Python Program to Check if a Number is Odd or Even
Python enumerate()
Python sum()
Python Operator Overloading
Python issubclass()
Python Set update()
Python String maketrans()
Python setattr()
Python Operators
Python Program to Display Calendar
Python String find()
Python Exception Handling Using try, except and finally statement
Python Machine Learning - Sebastian Raschka
Python List pop()
Python Dictionary values()
Python String encode()
Python List
Python Program to Check If a List is Empty
Python Program to Check Armstrong Number
Python Program to Append to a File
Python Program to Swap Two Variables
Python Program to Find the Size (Resolution) of a Image
Python Program to Find the Sum of Natural Numbers
Python List insert()