In python, the dictionary functions pop() and popitem() are used to remove items from a dictionary. In this tutorial we’ll look at these functions, their syntax and use-cases along with some examples.
Before we proceed, here’s a quick refresher on dictionaries in python – Dictionaries are a collection of items used for storing key to value mappings. They are mutable and hence we can update the dictionary by adding new key-value pairs, removing existing key-value pairs, or changing the value corresponding to a key. For more, check out our guide on dictionaries and other data structures in python.
How to remove items from a dictionary?
The python dictionary functions pop()
and popitem()
are used to remove items from a dictionary. The pop()
function removes the key-value pair of the key passed whereas the popitem()
function removes the last (based on LIFO order) key-value pair from the dictionary.
The pop() function
The pop()
dictionary function is used to remove a key from a dictionary and return its value. The following is the syntax:
sample_dict.pop(key, default)
Here, sample_dict is the dictionary from which you want to remove the items.
Parameters:
- key: The key corresponding to the key-value pair you want to remove from the dictionary.
- default (optional): The value to be returned if the key is not present in the dictionary.
Returns:
- If the key is in the dictionary, it removes the key and returns its value.
- If the key is not in the dictionary and the default is not provided, it raises a
KeyError
. - If the key is not in the dictionary and the default is provided, it returns the default.
Example 1: Key present in the dictionary
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
# print the dictionary
print("Shares original:", shares)
# remove 'GOOG' from shares
returned_val = shares.pop('GOOG')
# print the dictionary
print("Shares after removing GOOG:", shares)
print("Return value from pop:", returned_val)
Output:
Shares original: {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
Shares after removing GOOG: {'APPL': 100, 'MSFT': 200}
Return value from pop: 50
In the above example, we remove the key 'GOOG'
from the dictionary shares
using the pop()
function. It removed the key from the dictionary and returned 50
, the value corresponding to the removed key.
Example 2: Key not present in the dictionary and default not specified.
# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
# print the dictionary
print("Shares original:", shares)
# remove 'GOOG' from shares
returned_val = shares.pop('TSLA')
# print the dictionary
print("Shares after removing TSLA:", shares)
print("Return value from pop:", returned_val)
Output:
Shares original: {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-3d73afad69c6> in <module>
6
7 # remove 'GOOG' from shares
----> 8 returned_val = shares.pop('TSLA')
9
10 # print the dictionary
KeyError: 'TSLA'
In the above example, we try to remove 'TSLA'
which is not present in the dictionary using the pop()
function. Since no default return value is specified, it resulted in a KeyError
.
Example 3: Key not present but default specified.
# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
# print the dictionary
print("Shares original:", shares)
# remove 'GOOG' from shares
returned_val = shares.pop('TSLA', "Not present in dictionary")
# print the dictionary
print("Shares after removing TSLA:", shares)
print("Return value from pop:", returned_val)
Output:
Shares original: {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
Shares after removing TSLA: {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
Return value from pop: Not present in dictionary
In the above example, we again try to remove 'TSLA'
which is not present in the dictionary but this time we provide the default value to be returned. The dictionary shares
remains unchanged before and after the pop()
function and we get our custom "Not present in dictionary"
as the return value.
The popitem() function
The dictionary function popitem()
removes and returns the last key-value pair from the dictionary. That is, it removes items based on the Last-In-First-Out (LIFO) order. The following is the syntax:
sample_dict.popitem()
Here, sample_dict is the dictionary from which you want to remove the items.
Parameters: The popitem()
function does not take any parameters.
Returns: It removes and returns the last (key, value)
pair from the dictionary. If the dictionary is empty, it raises a KeyError
.
Note: From Python version 3.7, the LIFO order is guaranteed. In prior versions, the popitem()
function would return an arbitrary key-value pair from the dictionary.
Example 1: Removing the last dictionary item
# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
# print the dictionary
print("Shares:", shares)
# remove item
print("Removing item using popitem")
returned_val = shares.popitem()
print("Return Value:", returned_val)
print("Shares:", shares)
# add a new item to the dictionary
print("Adding a new item to shares")
shares.update({"TSLA": 80})
print("Shares:", shares)
# remove item
print("Removing item using popitem")
returned_val = shares.popitem()
print("Return Value:", returned_val)
print("Shares:", shares)
Output:
Shares: {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
Removing item using popitem
Return Value: ('MSFT', 200)
Shares: {'APPL': 100, 'GOOG': 50}
Adding a new item to shares
Shares: {'APPL': 100, 'GOOG': 50, 'TSLA': 80}
Removing item using popitem
Return Value: ('TSLA', 80)
Shares: {'APPL': 100, 'GOOG': 50}
In the above example, the popitem()
function is used to remove items from the dictionary shares
. It removes the last (key, value)
pair from the dictionary and returns it.
Example 2: Using popitem()
on an empty dictionary
# empty dictionary
shares = {}
# print the dictionary
print("Shares:", shares)
# remove item
print("Removing item using popitem")
returned_val = shares.popitem()
print("Return Value:", returned_val)
print("Shares:", shares)
Output:
Shares: {}
Removing item using popitem
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-9-6dcf5946355a> in <module>
6 # remove item
7 print("Removing item using popitem")
----> 8 returned_val = shares.popitem()
9 print("Return Value:", returned_val)
10 print("Shares:", shares)
KeyError: 'popitem(): dictionary is empty'
In the above example, a KeyError
is raised on using the popitem()
function on an empty dictionary.
For more on python dictionary functions, refer to the python docs.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.