Dictionary pop() method in Python

Spread the love

pop() method –

The pop method in dictionary remove a key-value pairs from a dictionary and return the value associated with the key.

syntax of pop() method –

dict.pop(key, default)

key – The key that you want to remove from the dictionary.

default – the value to return when the key is not present in the dictionary.

Pop a key value pair from a dictionary –

To pop or remove a key value pair from a dictionary, we can use the pop method.

Let’s create a dictionary which contains prices of stocks.

prices = {'icici': 710, 'reliance': 2617, 'airtel': 737}

Now, let’s say you want to remove the data of reliance stock and return the price of it.

In [2]: reliance_price = prices.pop('reliance')

In [3]: reliance_price
Out[3]: 2617

In [4]: prices
Out[4]: {'icici': 710, 'airtel': 737}

Pop a key value pair from the dictionary which is not present –

When you try to remove a key value pair that is not present in the dictionary and you have not provided a default value then you get a keyError.

In [5]: sbi_prices = prices.pop('sbi')
Traceback (most recent call last):

  File "C:\Users\BHOLA\AppData\Local\Temp\ipykernel_15860\2575497017.py", line 1, in <module>
    sbi_prices = prices.pop('sbi')

KeyError: 'sbi'

But if you provide a default value then that value will be returned if key is not found.

In [6]: sbi_prices = prices.pop('sbi', 0)

In [7]: sbi_prices
Out[7]: 0

In [8]: prices
Out[8]: {'icici': 710, 'airtel': 737}

Rating: 1 out of 5.

Leave a Reply