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 translate()
Python isinstance()
How to Get Started With Python?
Python Dictionary keys()
Python Program to Find All File with .txt Extension Present Inside a Directory
Deep Learning in Python - LazyProgrammer
Python map()
Python bytes()
Python Program to Trim Whitespace From a String
Python Program to Print all Prime Numbers in an Interval
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python float()
Python Program to Access Index of a List Using for Loop
Python List count()
Python dict()
Python Anonymous / Lambda Function
Python Global Keyword
Python Function Arguments
Deep Learning with Python - Francois Cholletf
Python Program to Get the File Name From the File Path
Python Program to Merge Two Dictionaries
Python reversed()
Python vars()
Python Program to Iterate Through Two Lists in Parallel
Python Program to Delete an Element From a Dictionary
Python staticmethod()
Python Numbers, Type Conversion and Mathematics
Python Program to Create a Countdown Timer
Python Dictionary pop()
Python round()
Python bytearray()
Python classmethod()