Python

popitem() method in dictionary

Click for All Topics

popitem() method in dictionary - Python

  • This method is used to remove last item from a dictionary.
  • This method doesn’t take any argument and returns last item from dictionary as a tuple.
  • The time complexity of this method is O(1).
  • If the dictionary is empty and you call popitem method with the dictionary then it will raise error KeyError .

Syntax –

dictionary.popitem()

 

Parameters –

  • return → return last key value pair.

 

Example –

				
					my_dict={10:100,20:200,30:300,40:400,50:500}
print("Original dictionary:\n",my_dict)

my_dict.popitem()
print("Updated Dictionary:",my_dict)

# Output - 
# Original dictionary:
 # {10: 100, 20: 200, 30: 300, 40: 400, 50: 500}
# Updated Dictionary: {10: 100, 20: 200, 30: 300, 40: 400}
				
			
  • In the above example, first we create a dictionary with some items and store it in my_dict variable.
  • After creating a dictionary print the original dictionary on the output screen.
  • Then pop last item from the dictionary by using the .popitem() method.
  • Finally print the updated dictionary on the output screen.

Example –

				
					test_marks={'saurabh':8,'parn':9,'anurag':9,'vikram':6}
print('Original Dictionary:',test_marks)

n=len(test_marks)
for i in range(n):
	item=test_marks.popitem()
	print('name: '+item[0]+', marks: '+str(item[1]))

# Output -
# Original Dictionary: {'saurabh': 8, 'parn': 9, 'anurag': 9, 'vikram': 6}
# name: vikram, marks: 6
# name: anurag, marks: 9
# name: parn, marks: 9
# name: saurabh, marks: 8
				
			

Example –

				
					# Print the total marks obtained by student 

student_marks={'hindi':86,'math':88,'English':58,'Physics':87,'chemistry':87}
print("Original Dictionary:\n",student_marks)
n=len(student_marks)
s=0
for i in range(n):
	item=student_marks.popitem()
	s=s+item[1]

print("Total marks obtained by student:",s)
print("Updated Dictionary:",student_marks)

# Output -
# Original Dictionary:
# {'hindi': 86, 'math': 88, 'English': 58, 'Physics': 87, 'chemistry': 87}
# Total marks obtained by student: 406
# Updated Dictionary: {}