Python Dictionary popitem() Method With Example

Python Dictionary popitem

Now, we are going to learn about the popitem method. Whenever we are required to remove the last added key-value pair from the dictionary, we can do that using the popitem method. So, we can simply say that the popitem method removes the last inserted key-value pair from the dictionary.

Remember, if the dictionary is empty, and you call the popitem method over the dictionary, then it raises a KeyError.

Let’s now have a look at a program, for a better understanding of the popitem method –

Python Dictionary popitem() Method

In the above program, you can see that we have a sample dictionary (you can consider an example of your own, but here we are understanding the method, so we have created a sample dictionary)

In the dictionary, you can see that the element with the key ‘four’ is the last inserted element. So, according to the definition of the method, the last inserted element would get removed.

We also printed the dictionary before and after calling the method.

Let’s now have a look at the output –

C:\Users\GyaniPandit\Desktop\python> python dictionary.py
{‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4}
{‘one’: 1, ‘two’: 2, ‘three’: 3}
(‘four’, 4)

As you can see, the element with key ‘four’ is last inserted into the dictionary, according to the program and then we call the popitem method, and the last inserted element is removed.

The popitem method returns the removed element as a tuple, as can be seen in the output.

So, if you ever need to remove the last inserted key-value pair, you can make use of the popitem method.