Python Dictionary pop() Method

The dictionary pop() is a built-in Python function that “removes the specified element from the dictionary”. The pop() method removes and returns an item from the dictionary having the given key.

Syntax

dictionary.pop(keyname, defaultvalue)

Parameters

The pop() method takes two parameters:

  1. key – The key is a parameter that needs to be searched for removal.
  2. defaultValue – The defaultValue is a value to be returned when the key is not in the dictionary.

Return Value

The pop() method returns:

  1. If the key is found: remove/pop the element from the dictionary.
  2. If the key is not found: the value is specified as the second argument (default).
  3. If the key is not found and the default argument is not specified – the KeyError exception is raised.

Example 1

origDict = { 
  'shopping': 'flipkart',
  'transport': 'ola',
  'banking': 'paytm',
  'hotel': 'oyo rooms'
 }

removedItem = origDict.pop('shopping')
print(origDict)
print(removedItem)

In the above example, we have removed the item whose key name is shopping.

Output

Python Dictionary Pop Example | Pop() Method Tutorial

We have got the Flipkart as removedItem.

If a key is found, it removes an element from the dictionary. 

If a key is not found and the default argument is not specified, then the KeyError exception is raised.

Example 2

origDict = { 
  'shopping': 'flipkart',
  'transport': 'ola',
  'banking': 'paytm',
  'hotel': 'oyo rooms'
 }
removedItem = origDict.pop('transport', 'ola')
print(origDict)
print(removedItem)

In the above example, we have provided the app key as an argument, which is not in the dictionary, and ola as a value, which is in the dictionary.

Output

Pop() Method Tutorial

Example 3

origDict = { 
  'shopping': 'flipkart',
  'transport': 'ola',
  'banking': 'paytm',
  'hotel': 'oyo rooms'
 }
removedItem = origDict.pop('mobile')
print(origDict)
print(removedItem)

Output

Python Dictionary Pop() Tutorial

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.