Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
The pop() Method | Dictionary
Python Data Structures
course content

Course Content

Python Data Structures

Python Data Structures

1. List
2. Dictionary
3. Tuple
4. Set

book
The pop() Method

The pop() method in Python dictionaries allows you to remove a key-value pair based on its key and returns the corresponding value. This method is particularly useful when you need to extract and process a value while simultaneously removing it from the dictionary.

The syntax is:

123456789101112
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "copies": 5 } # Remove the 'copies' key and retrieve its value removed_copies = book.pop("copies") print("Updated dictionary:", book) print("Removed value:", removed_copies)
copy

If the key does not exist in the dictionary, Python raises a KeyError exception.

12345678
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813 } # Attempting to remove a non-existent key removed_genre = book.pop("genre")
copy
Task
test

Swipe to show code editor

The book's availability status is being tracked elsewhere. Use the pop() method to remove the available key from the book dictionary and print its value.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 7
toggle bottom row

book
The pop() Method

The pop() method in Python dictionaries allows you to remove a key-value pair based on its key and returns the corresponding value. This method is particularly useful when you need to extract and process a value while simultaneously removing it from the dictionary.

The syntax is:

123456789101112
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "copies": 5 } # Remove the 'copies' key and retrieve its value removed_copies = book.pop("copies") print("Updated dictionary:", book) print("Removed value:", removed_copies)
copy

If the key does not exist in the dictionary, Python raises a KeyError exception.

12345678
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813 } # Attempting to remove a non-existent key removed_genre = book.pop("genre")
copy
Task
test

Swipe to show code editor

The book's availability status is being tracked elsewhere. Use the pop() method to remove the available key from the book dictionary and print its value.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 7
Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
We're sorry to hear that something went wrong. What happened?
some-alt