Python Dictionary pop() Method

This Python article covers the Python dictionary pop() method, specifically, its definition, syntax, parameter(s), and return type. Additionally, we’ll provide some examples on how dict.pop() is used in practice. So, let’s get started! đŸ™‚

Related Article:

Definition

The dict.pop() method both removes and returns a specified (key-value) pair element from a dictionary.

Syntax

dict.pop(key, default_value)

Parameters

  • key: Declare the key whose (key-value) pair element has to be both returned and removed.
  • default_value: This is the default-value that will be returned if the specified key is not in the dictionary.

Return-Value

  • If the specified key exists in the dictionary, dict.pop() returns the value grouped to the deleted (key-value) pair element.
  • If the key doesn’t exist, dict.pop()returns the specified default value.
  • If the key is not present in the dictionary and the default value is not specified, dict.pop()returns a KeyError.

Example 1: Key Exists

An example of a simple Python dict.pop() method operation applied to a Python Dictionary:

computer_items = {'laptop': 200.00, 'smart-phone': 300.00, 'camera': 20.00, 'desktop': 500.00}
laptop_item = computer_items.pop('laptop')
 
print('The selected laptops price is: ', laptop_item)
print('Updated computer items after purchase: ', computer_items)

Output:

The selected laptops price is:  200.0
Updated computer items after purchase:  {'smart-phone': 300.0, 'camera': 20.0, 'desktop': 500.0}

The dict.pop() method removes the whole (laptop': 200.00) key-value pair element from the computer_items dictionary, but only stores the value part in the computer_item variable which is why 200.00 dollars is returned when the laptop_item variable is printed.

When the computer_items dictionary gets reprinted after the dict.pop() operation has been performed, the (laptop': 200.00) key-value pair element is no longer shown in the computer_items dictionary because the dict.pop() method completely removed the element from the dictionary.

Example 2: Key Doesn’t Exist

Next, let’s dive into an example of removing an element that’s not in a Python Dictionary. Again, we use dict.pop():

grocery_items = {'bread': 1, 'eggs': 3, 'milk': 3, 'potatoes': 6}
grape_items = grocery_items.pop('grape')
 
print(grape_items)

Output:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 2, in <module>
    grape_items = grocery_items.pop('grape')
KeyError: 'grape'

As the result shows, if you use the dict.pop() method to try and remove a (key-value) pair element that is not in the dictionary, Python will raise a KeyError and print the attempted key that was passed to the dict.pop() method.

Example 3: Default Value

The following example sets a default value to be returned if the key passed to the dict.pop() method is not in the dictionary:

store_items = {'pens': 6, 'notebooks': 5, 'desks': 3, 'tables': 3, 'shelves': 4, 'power-strips': 6}
computers_not_in_stock = store_items.pop('computers', 3)
 
print('The quantity of computers not in stock are: ', computers_not_in_stock)
print('The items in stock are: ', store_items)

Output:

The quantity of computers not in stock are:  3
The items in stock are:  {'pens': 6, 'notebooks': 5, 'desks': 3, 'tables': 3, 'shelves': 4, 'power-strips': 6}

As the printed results show, if a (key-value) pair element is not found in a dictionary using the dict.pop() method, then the associated value still gets stored as a default-value in a declared variable., where the variable can later be called to show the default-value that’s not in the Python dictionary.

Example 4: dict.pop() vs del

The following example highlights the difference between the dict.pop() and del methods applied to a Python dictionary:

kitchen_items = {'coffee': 'expresso', 'jelly': 'grape', 'bread': 'wheat', 'tortilla': 'flower'}
del kitchen_items['coffee']
removed_bread = kitchen_items.pop('bread')
 
print('kitchen items in cabinet: ', kitchen_items)
print('bread not found in kitchen cabinet: ', removed_bread)

Output:

kitchen items in cabinet:  {'jelly': 'grape', 'tortilla': 'flower'}
bread not found in kitchen cabinet:  wheat

As the results show, the dict.pop() method returns a value that is associated with the key that was removed from the Python Dictionary.

The Python del keyword differs from the dict.pop() method in that once a key gets deleted from a dictionary, it does not return a value and a KeyError is raised.

Example 5: Remove Multiple Keys

An example of how to remove multiple keys from a Python Dictionary using the dict.pop() method:

identities = {1: 'sarah', 2: 'kim', 3: 'bob', 4: 'tim'}
remove_keys = [1, 3]
 
for key in remove_keys:
   identities.pop(key)
 
print(identities)
# {2: 'kim', 4: 'tim'}

You use the dict.pop() method to remove multiple keys from a Python Dictionary:

  • First a list of the keys to be removed and stored in a variable.
  • Second, declare a for-loop that iterates through the list of keys to be removed.
  • Third, apply the pop method to the dictionary in each iteration, passing the current iterated key from the list to be removed.
  • Fourth, print the identities dictionary after the for-loop operation; this shows that multiple keys were removed from the dictionary.

Example 6: Delete If Exists

An example of deleting an item from a Python dictionary with the dict.pop() method, only if it exists in the dictionary:

office_items = {'pens': 6, 'shelves': 3, 'chairs': 2, 'computers': 3, 'notebooks': 10, 'keyboards': 3}
check_coffee = office_items.pop('coffee_maker', None)

print(check_coffee)
# None

So, if the key passed to the dict.pop() method is in the office_items dictionary, the keys value will be returned. Otherwise, if the key passed to the dict.pop() method is not found in the office items dictionary, the None value will be returned for the key that was not found in the dictionary.

Python Dictionary pop() Time Complexity

Complexity Class:

  • Average Case: O(1), Constant Time
  • Amortise Worst Case: O(N), Linear Time