Saturday, November 16, 2024
Google search engine
HomeLanguagesPython Dictionary popitem() method

Python Dictionary popitem() method

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}
 
# Printing initial dict
print("Before using popitem(), test_dict: ", test_dict)
 
# using popitem() to return+
# remove the last keym value pair
res = test_dict.popitem()
 
# Printing the pair returned
print('The key, value pair returned is : ', res)
 
# Printing dict after deletion
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




# Python 3 code to demonstrate
# application of popitem()
 
# initializing dictionary
test_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2}
 
# Printing initial dict
print("The dictionary before deletion : " + str(test_dict))
 
n = len(test_dict)
 
# using popitem to assign ranks
for i in range(0, n):
    print("Rank " + str(i + 1) + " " + str(test_dict.popitem()))
 
# Printing end dict
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 : {}

RELATED ARTICLES

Most Popular

Recent Comments