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 Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Get Current time
Python Program to Find the Size (Resolution) of a Image
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Remove Duplicate Element From a List
Python String encode()
Python Tuple
Python zip()
Python getattr()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Variables, Constants and Literals
Python Dictionary values()
Python Program to Remove Punctuations From a String
Python Input, Output and Import
Python Program to Get Line Count of a File
Python exec()
Python Program to Create a Countdown Timer
Python property()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Find Armstrong Number in an Interval
Python Dictionary fromkeys()
Python dir()
Python Iterators
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Calculate the Area of a Triangle
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Node.js vs Python for Backend Development
Python Program to Split a List Into Evenly Sized Chunks
APIs in Node.js vs Python - A Comparison
Python Program to Print Hello world!
Python callable()
Python Program to Print the Fibonacci sequence