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 locals()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Check If Two Strings are Anagram
Python List copy()
Python String rsplit()
Python setattr()
Python if...else Statement
Python Program to Compute all the Permutation of the String
Python Custom Exceptions
Python reversed()
Python Program to Slice Lists
Python String isdecimal()
Python Program to Count the Occurrence of an Item in a List
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Randomly Select an Element From the List
Python print()
Python Program to Access Index of a List Using for Loop
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Check if a Key is Already Present in a Dictionary
Python Input, Output and Import
Python Set discard()
Python Get Current time
Python Program to Transpose a Matrix
Python float()
Python Set issubset()
Python Program to Check If a List is Empty
Python complex()
Python len()
Python Program to Check If a String Is a Number (Float)
Python List reverse()
Python Program to Get a Substring of a String
Python String translate()