Skip to content

Python dictionary pop function | Example code

  • by

Using the pop() function you can remove the dictionary element in Python. This method actually removes and returns the specified element from the dictionary.

dictionary.pop(keyname, defaultvalue) 

default value (Optional) – value to return if the specified key does not exist.

Note: If the specified key is not present, it throws an error KeyError.

Example dictionary pop function in Python

Simple example code.

marks = {'Physics': 80, 'Chemistry': 90, 'Math': 100}

element = marks.pop('Chemistry')

print('Popped Marks:', element)
print(marks)

Output:

Python dictionary pop function

Another example

If the key is not present, we can set the default value to avoid the error KeyError.

marks = {'Physics': 80, 'Chemistry': 90, 'Math': 100}

element = marks.pop('Code', 0)

print('Popped Marks:', element)
print(marks)

Output: Popped Marks: 0

Do comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *