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 aKeyError
error if the dictionary is empty.
Related posts:
Python strftime()
Python min()
Python break and continue
Python Program to Get the Class Name of an Instance
Python len()
Python Program to Check if a Number is Positive, Negative or 0
Python Global Keyword
Python Program to Calculate the Area of a Triangle
Python Program to Check if a Number is Odd or Even
Python float()
Python String islower()
Python Program to Return Multiple Values From a Function
Python String splitlines()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String lstrip()
Python Set issuperset()
Python Program to Get the File Name From the File Path
Python Program to Display Calendar
Python List copy()
Python Program to Check If a String Is a Number (Float)
Python Anonymous / Lambda Function
Python Program to Print all Prime Numbers in an Interval
Python Program to Safely Create a Nested Directory
Python Program to Find the Factors of a Number
Python Program to Concatenate Two Lists
Python String isalpha()
Python tuple()
Python List sort()
Python List clear()
Python Inheritance
Python Program to Multiply Two Matrices
Python Program to Add Two Matrices