Python Dictionary pop function

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

dictionary_name.pop(key, default_value)

Python Dictionary pop Example

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

# Python Dictionary pop Example

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

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

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

Dictionary pop function Example 2

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

# Python Dictionary pop Example

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 pop function output

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
>>> 

Pop Dictionary items Example 3

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

# Python Dictionary pop Example

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