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 Program to Append to a File
Python Set union()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Deep Learning with Python - Francois Chollet
Python String endswith()
Python Program to Convert String to Datetime
Python Program to Display Fibonacci Sequence Using Recursion
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python String maketrans()
Python Program to Find Hash of File
Python String rsplit()
Python any()
Python String capitalize()
Python Program to Calculate the Area of a Triangle
Python String casefold()
Python round()
Python Program to Find the Sum of Natural Numbers
Python Program to Reverse a Number
Python List
Python Program to Merge Two Dictionaries
Python Program to Illustrate Different Set Operations
Python String zfill()
Python String isidentifier()
Python String format()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
APIs in Node.js vs Python - A Comparison
Python setattr()
Python while Loop
Python Program to Return Multiple Values From a Function
Python min()
Python callable()
Python Program to Check If a List is Empty