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:
- key – The key is a parameter that needs to be searched for removal.
- defaultValue – The defaultValue is a value to be returned when the key is not in the dictionary.
Return Value
The pop() method returns:
- If the key is found: remove/pop the element from the dictionary.
- If the key is not found: the value is specified as the second argument (default).
- 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
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
Example 3
origDict = {
'shopping': 'flipkart',
'transport': 'ola',
'banking': 'paytm',
'hotel': 'oyo rooms'
}
removedItem = origDict.pop('mobile')
print(origDict)
print(removedItem)
Output
That’s it.