In this Python tutorial, you will learn what popitem() method of dictionary dict class does, its syntax, and how to use this method to remove an item from the dictionary, with example programs.

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.

Syntax

The syntax of dict.popitem() is

dict.popitem()

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

ADVERTISEMENT

Examples (3)

1. Pop an item from dictionary

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

Python Program

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

Program Output

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

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

2. Insert items to dictionary and then pop item from dictionary (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

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

Program Output

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

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

3. Pop items from dictionary in a 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

myDictionary = {'a': 58, 'b': 61, 'c': 39}
while myDictionary:
    item = myDictionary.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.