Python Dictionary pop function

Python Dictionary pop function is used to remove an item at a given key position and prints the removed value. The syntax behind this is:

dictionary_name.pop(key, default_value)

Python Dictionary pop Example

The pop function removes key-value pairs at a given key and prints the value.

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

print("\nRemoved Item      :  ",  myDict.pop(3))
print("Dictionary Items  :  ",  myDict)

print("\nRemoved Item      :  ",  myDict.pop(1))
print("Dictionary Items  :  ",  myDict)
Python Dictionary pop 1

In this program, we are trying to pop or remove a non-exiting Dictionary item. As you can see, Python is throwing an error.

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

# Pop Non-existing Values
print("\nRemoved Item      :  ",  myDict.pop(5))
print("Dictionary Items  :  ",  myDict)
Dictionary Items:  {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 5, in <module>
    print("\nRemoved Item      :  ",  myDict.pop(5))
KeyError: 5
>>> 

In this program, we are using the second argument to display the default value. The below pop code returns Sorry!! No Item exits message if you are trying to remove the non-existing item from the dictionary.

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

# Pop Non-existing Values
print("\nRemoved Item      :  ",  myDict.pop(5, 'Sorry!! No Item exists'))
Dictionary Items:  {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}

Removed Item      :   Sorry!! No Item exists