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 String isspace()
Python Program to Check Armstrong Number
Python memoryview()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Check Prime Number
Python String rstrip()
Python String capitalize()
Python Program to Generate a Random Number
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python String find()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
APIs in Node.js vs Python - A Comparison
Python Type Conversion and Type Casting
Python Set difference_update()
Python Statement, Indentation and Comments
Python RegEx
Python Set symmetric_difference_update()
Machine Learning with Python for everyone - Mark E.Fenner
Python Dictionary items()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Get the Full Path of the Current Working Directory
Python Program to Check If a String Is a Number (Float)
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Directory and Files Management
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python List Comprehension
Python Program to Delete an Element From a Dictionary
Python Set symmetric_difference()
Python Program to Check If a List is Empty
Python Program to Sort a Dictionary by Value
Python min()
Python Program to Get Line Count of a File