Python dictionary popitem function | Example code

  • by

If you want to remove the last inserted element from the dictionary then use the dictionary popitem function in Python. This method simply removes and returns the last element (key, value) pair inserted into the dictionary.

dict.popitem()

Python dictionary popitem example

Simple example code.

dict1 = {"A": 7, "B": 1, "C": 2}

res = dict1.popitem()

print("Removed", res)
print(dict1)

Output:

Python dictionary popitem function

Note: In Python versions before 3.7, the popitem() the method removes a random item.

Do comment if you have any doubts and suggestions on this Python dictionary function.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.