AppDividend
Latest Code Tutorials

Python Dictionary Pop Example | Pop() Method Tutorial

0 15

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see Python Dictionary Pop Example | Pop() Method. The dictionary pop() method removes the specified element from a dictionary. The value of the removed element is the removed item of the pop() method. The pop() method removes and returns an element from a dictionary provided the given key.

Python Dictionary Pop Example

The syntax for the pop() method in Dictionary Python is following.

dictionary.pop(keyname, defaultvalue)

Let see the following example.

# app.py

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.

The output is following.

 

Python Dictionary Pop Example | Pop() Method Tutorial

We have got the Flipkart as removedItem.

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

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

Let see the scenario, where the key and value is specified in the dictionary.

# app.py

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. See the below output.

 

Pop() Method Tutorial

See the following scenario where the key is not present in the dictionary.

# app.py

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

The output is following.

 

Python Dictionary Pop() Tutorial

Finally, Python Dictionary Pop Example | Pop() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

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