Dictionary popitem() Method in Python

Python Dictionary popitem() Method

The popitem() method in Python dictionaries is used to remove and return an arbitrary (key, value) pair from the dictionary. This method is useful when you want to retrieve and delete an item from the dictionary, but you don't care about the specific key-value pair that gets removed. Note that the choice of which item to remove is arbitrary and may vary between different Python implementations.

Syntax of the popitem() method:

(key, value) = dictionary.popitem()
  • (key, value): The popitem() method returns a tuple containing the key and value of the item that was removed from the dictionary.

Now, let's see an example of how to use the popitem() method:

Example:

# Sample dictionary
fruits_stock = {'apple': 10, 'banana': 15, 'orange': 20, 'grapes': 8}

# Remove and retrieve an arbitrary (key, value) pair
removed_item = fruits_stock.popitem()

# Print the removed (key, value) pair and the updated dictionary
print("Removed Item:", removed_item)
print("Updated Dictionary:", fruits_stock)

Output:

Removed Item: ('grapes', 8)
Updated Dictionary: {'apple': 10, 'banana': 15, 'orange': 20}

In this example, the popitem() method removes an arbitrary (key, value) pair from the fruits_stock dictionary and returns it as a tuple. The removed item could be any key-value pair present in the dictionary. After calling popitem(), the dictionary no longer contains the removed key-value pair.

It's important to note that if the dictionary is empty, calling popitem() will raise a KeyError. Therefore, it's a good practice to check if the dictionary is not empty before using this method. You can use the if statement or use a try-except block to handle the situation if the dictionary is empty.