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 strptime()
Python Set copy()
Python Program to Get File Creation and Modification Date
Python Program to Add Two Matrices
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Statement, Indentation and Comments
Python set()
Python Set clear()
Python sorted()
Python Program to Check If Two Strings are Anagram
Python Program to Find Hash of File
Python Program to Find LCM
Python Dictionary keys()
Python String istitle()
Python dict()
Python Operators
Python String index()
Python Anonymous / Lambda Function
Python chr()
Python property()
Python exec()
Python Program to Measure the Elapsed Time in Python
Python String split()
Python list()
Python Program to Get the Class Name of an Instance
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Merge Mails
Python range()
Python vars()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Print the Fibonacci sequence
Python Dictionary clear()