AppDividend
Latest Code Tutorials

Python Dictionary Pop Example | Python dict Pop()

0

In this tutorial, we will see Python Dictionary Pop Example | Python dict 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 dict pop() method in Dictionary Python is the 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 the 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 the KeyError exception is raised.

Let see the scenario, where the key and value are 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 the following.

Python Dictionary Pop() Tutorial

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

Recommended Posts

Python Dictionary Get Example

How To Convert Python Dictionary To JSON

Python Dictionary Keys Example

Python Dictionary fromKeys Example

Python Dictionary Copy Example

Leave A Reply

Your email address will not be published.

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