Dictionary popitem() methods in Python

Spread the love

popitem() method –

The popitem() method removes and return the last key value pair that is inserted in the dictionary.

syntax of popitem() method –


Let’s say we have a dictionary which contains stock prices.

In [1]: prices = {'icici': 710, 'reliance': 2617, 'airtel': 737}

Now, since we added the airtel prices at last, it will be removed and returned first.

In [2]: returned_value = prices.popitem()

In [3]: returned_value
Out[3]: ('airtel', 737)

In [4]: prices
Out[4]: {'icici': 710, 'reliance': 2617}

Let’s look at one more time. Let’s add the stock price of sbi.

In [5]: prices['sbi'] = 495

In [6]: prices
Out[6]: {'icici': 710, 'reliance': 2617, 'sbi': 495}

Now, if we use the popitem() method then sbi stock will be removed from the dictionary as popitem() follows Last In, First out (LIFO) order.

In [7]: returned_value = prices.popitem()

In [8]: returned_value
Out[8]: ('sbi', 495)

In [9]: prices
Out[9]: {'icici': 710, 'reliance': 2617}

Rating: 1 out of 5.

Leave a Reply