Python dictionary pop() method [With Examples]

In this Python article, we will explore the Python dictionary pop() method, which is a valuable tool for safely removing dictionary values.

We will discuss its syntax, usage, and some practical examples to help us utilize this method effectively.

Dictionary pop() method in Python

Below are the topics that we are doing to discuss in this article:

  • Introduction to Python Dictionary pop() method
  • Syntax of the pop() method
  • Purpose and use cases of the pop() method

Python Dictionary pop() method

The pop() function is used to remove a specific element from a Python dictionary, thereby altering the dictionary in-place. This method removes the item with the provided key and returns the value. If the provided key is not found, it returns a default value (if provided).

Here’s the basic syntax for the pop() method:

dictionary.pop(key, default)
  • key: The key which is to be searched for removal.
  • default: The value which is to return if the key is not found. This parameter is optional.

pop() method in Python Dictionary Examples

Let’s take a look at some examples of using the pop() method.

Example#1 Basic Usage

student = {
    'name': 'John Doe',
    'age': 20,
    'course': 'Computer Science'
}

name = student.pop('name')
print(name)  
print(student)  

In this example, we used the pop() method to remove the ‘name’ entry from the student Python dictionary. The method returns the value of the removed entry and the Python dictionary is updated to reflect the removal.

Output:

Python dictionary pop method
Python dictionary pop method

Example#2 Handling Non-Existent Keys

What happens if we try to pop a key that doesn’t exist in the Python dictionary? Python will raise a KeyError. To handle this, we can provide a default value that will be returned when the key doesn’t exist.

student = {
    'name': 'John Doe',
    'age': 20,
    'course': 'Computer Science'
}

grade = student.pop('grade', 'Not Found')
print(grade)  

In this example, we tried to remove the key ‘grade’, which doesn’t exist in the student Python dictionary. Instead of raising a KeyError, Python returns the default value ‘Not Found’.

Output:

Python dictionary pop method example
Python dictionary pop method example

Conclusion

The Python dictionary pop() method is a powerful tool when working with Python dictionaries. It allows you to remove key-value pairs from a dictionary, which can be useful in a variety of programming scenarios.

You may also like to read the following articles: