Python Dictionary popitem()

Python Dictionary popitem() method removes and returns a (key, value) pair from the dictionary. If you call popitem() method on an empty dictionary, it raises KeyError.

popitem() method pops items from the dictionary in Last-In-First-Out order. We shall also go through an example that supports this statement.

In this tutorial, we will learn the syntax of popitem() and its usage in different scenarios using examples.

Syntax – pop()

The syntax of dict.popitem() is

dict.popitem()

popitem() returns a tuple containing key:value pair as (key, value).

Example 1 – Python dict.popitem()

In this example, we will take a dictionary, and delete a key:value pair using popitem() method.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
item = dictionary.popitem()
print(item)
print(dictionary)
Try Online

Program Output

('c', 39)
{'a': 58, 'b': 61}

The key:value pair (‘c’, 39) is removed and returned from the dictionary.

Example 2 – Python dict.popitem() – Last-In-First-Out order

In this example, we will take an empty dictionary, add key:value pairs to it one by one. As a result, we will know the order in which the items are added to the dictionary. Then, we shall call popitem() and observe the order of items that will be removed.

Python Program

dictionary = {}
dictionary['a'] = 58
dictionary['b'] = 61
dictionary['c'] = 39
item = dictionary.popitem()
print(item)
item = dictionary.popitem()
print(item)
item = dictionary.popitem()
print(item)
Try Online

Program Output

('c', 39)
('b', 61)
('a', 58)

The items have been removed in Last-In-First-Out order.

Example 3 – Python dict.popitem() with while loop

You can use dict.popitem() with while loop to destructively iterate over the dictionary.

In this example, we will destructively iterate over a dictionary using while loop and dict.popitem() method.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
while dictionary:
    item = dictionary.popitem()
    print(item)
Try Online

Program Output

('c', 39)
('b', 61)
('a', 58)

Conclusion

In this Python Tutorial, we learned about Python Dictionary method dict.popitem(). We have gone through the syntax of popitem(), and its usage with example programs based on different scenarios.