Python Dictionary popitem():

The popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple. However, if we call this method on an empty dictionary, it raises a KeyError exception.

Method signature

The signature for the popitem() method is as shown below. Here, d refers to the dictionary and t stores the tuple returned by this method.

t=d.popitem()

Method parameters and return type

  • The popitem() doesn’t take any parameter.
  • However, it returns the last key-value pair inserted in the dictionary as a tuple.

Python Dictionary popitem Examples:

Example 1: In this example, let us take a dictionary referred to as d, mapping decimal numbers to color names. Furthermore, t is used here to store the tuple. Since the last key value pair is the one with key 3. Thus it will be deleted from the dictionary.

#Initializing 
d={1:"Red",2:"Blue",3:"Green"}
#Printing 
print("Before popitem Dictionary d is ",d)
# Using popitem method
t=d.popitem()
#Printing
print("Value popped out is ",t) 
print("After popitem Dictionary d is ",d)

Output

Before popitem Dictionary d is  {1: 'Red', 2: 'Blue', 3: 'Green'}
Value popped out is  (3, 'Green')
After popitem Dictionary d is  {1: 'Red', 2: 'Blue'}

Example 2: In this example, let us take a dictionary referred to as d, mapping numbers to city names. Firstly, we will add one more key-value pair to a dictionary. Later, we pop two items out of the dictionary using popitem method.

#Initializing 
d={1:"Delhi",2:"Chennai",3:"Hyderabad"}
#Adding one more pair 
d.update({4:"Mumbai"})
# Using popitem method and printing
t=d.popitem()
print("Item popped is ",t)
t=d.popitem()
print("Item popped is ",t)

Output

Item popped is  (4, 'Mumbai')
Item popped is  (3, 'Hyderabad')

Example 3:

In this example, We will take a dictionary mapping decimal numbers to roman numerals. We will use a while loop for popping all the items out of the dictionary. As a result, it prints all the values popped out one by one. We will also try to pop an item from an empty dictionary to raise a keyerror exception.

#Initializing 
d={1:"I",5:"V",10:"X",50:"L",100:"C",500:"D",1000:"M"}
# Using popitem method and printing
while d :
	t=d.popitem()
	print("Value popped out is ",t)
#Popping one more time
t=d.popitem()
print("Value popped out from empty list is ",t)

Output

Value popped out is  (1000, 'M')
Value popped out is  (500, 'D')
Value popped out is  (100, 'C')
Value popped out is  (50, 'L')
Value popped out is  (10, 'X')
Value popped out is  (5, 'V')
Value popped out is  (1, 'I')
Traceback (most recent call last):
  File "main.py", line 6, in 
    t=d.popitem()
KeyError: 'popitem(): dictionary is empty'

Conclusion

The popitem() method removes and returns one key-value pair at a time from the dictionary. However, in the case of an empty list, this method will raise a keyerror exception.

References

Happy Learning 🙂

Leave A Comment