Python dictionary popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple.
Python Dictionary popitem() Method Syntax:
Syntax : dict.popitem()
Parameters : None
Returns : A tuple containing the arbitrary key-value pair from dictionary. That pair is removed from dictionary.
Note: popitem() method return keyError if dictionary is empty.
Python Dictionary popitem() Method Example:
Python3
d = { 1 : '001' , 2 : '010' , 3 : '011' }
print (d.popitem())
|
Output:
(3, '011')
Example 1: Demonstrating the use of popitem()
Here we are going to use Python dict popitem() method to pop the last element.
Python3
test_dict = { "Nikhil" : 7 , "Akshat" : 1 , "Akash" : 2 }
print ( "Before using popitem(), test_dict: " , test_dict)
res = test_dict.popitem()
print ( 'The key, value pair returned is : ' , res)
print ( "After using popitem(), test_dict: " , test_dict)
|
Output :
Before using popitem(), test_dict: {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
The key, value pair returned is : ('Akash', 2)
After using popitem(), test_dict: {'Nikhil': 7, 'Akshat': 1}
Practical Application: This particular function can be used to remove items and it’s details one by one.
Example 2: Demonstrating the application of popitem()
Python3
test_dict = { "Nikhil" : 7 , "Akshat" : 1 , "Akash" : 2 }
print ( "The dictionary before deletion : " + str (test_dict))
n = len (test_dict)
for i in range ( 0 , n):
print ( "Rank " + str (i + 1 ) + " " + str (test_dict.popitem()))
print ( "The dictionary after deletion : " + str (test_dict))
|
Output :
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Rank 1 ('Akash', 2)
Rank 2 ('Akshat', 1)
Rank 3 ('Nikhil', 7)
The dictionary after deletion : {}