Python dictionary popitem() method [With Examples]

In this article, we will discuss the Python Dictionary popitem() method which is a useful function that facilitates the removal of elements from a dictionary.

In addition to this, we will discuss the popitem() method syntax, usage, and examples.

Dictionary popitem() method in Python

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

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

Python Dictionary popitem() method

The popitem() method in Python is a built-in method used with dictionaries. It removes and returns the last key-value pair inserted into the Python dictionary as a tuple. This method is useful when we need to remove items from a Python dictionary while also retrieving their key-value pairs.

Syntax of the popitem() Method is as follows:

dictionary.popitem()

popitem() method in Python Dictionary Examples

Let’s dive into some examples to better understand the popitem() method in action:

Example#1 Using the popitem() Method

student_data = {'Name': 'Alice', 'Age': 21, 'Course': 'Computer Science'}
removed_item = student_data.popitem()
print("Removed item:", removed_item)
print("Updated dictionary:", student_data)

The popitem() method is primarily used to remove the last item in a Python dictionary. As shown, the last item in the student_data Python dictionary (‘Course’, ‘Computer Science’) is removed using the popitem() method, and the remaining Python dictionary only contains 'Name' and 'Age'.

Output:

Python dictionary popitem method
Python dictionary popitem method

Example#2 Handling Empty Dictionaries

empty_dict = {}
try:
    removed_item = empty_dict.popitem()
except KeyError:
    print("The dictionary is empty.")

When the popitem() method is applied to an empty Python dictionary, a KeyError is raised. To avoid this, we can use exception handling to display a custom error message.

Output:

Python dictionary popitem method example
Python dictionary popitem method example

Example#3 Removing a State from a List of States and Capitals

states_and_capitals = {
    'California': 'Sacramento',
    'Texas': 'Austin',
    'Florida': 'Tallahassee',
    'New York': 'Albany',
    'Illinois': 'Springfield'
}

removed_state_and_capital = states_and_capitals.popitem()
print("Removed state and capital:", removed_state_and_capital)
print("Remaining states and capitals:", states_and_capitals)

In this example, the popitem() method removes the last state-capital pair (‘Illinois’, ‘Springfield’) from the Python dictionary. The remaining states and capitals are then printed.

Output:

Dictionary popitem method in Python
Dictionary popitem method in Python

Example#4 Picking a Random US State for a Road Trip

Imagine we want to randomly select a US state for a road trip. We can use the popitem() method to remove a state from a Python list of states so it won’t be selected again.

import random

us_states = {
    1: 'Alabama',
    2: 'Alaska',
    3: 'Arizona',
    4: 'Arkansas',
    5: 'California',
    # More US states...
}

random_state_key = random.choice(list(us_states.keys()))
selected_state = us_states[random_state_key]
us_states.popitem()

print("Selected state for road trip:", selected_state)
print("Remaining states:", us_states)

In this example, a random state key is chosen from the Python list of US states. The popitem() method is then used to remove the last state from the list, ensuring it won’t be chosen again in future iterations.

Output:

Dictionary popitem method in Python example
Dictionary popitem method in Python example

Conclusion

The Python dictionary popitem() method is an essential function when working with dictionaries in Python. It allows users to remove the last item in a dictionary easily and returns a tuple containing the key-value pair.

You may also like to read the following articles: