Python popitem() Function

The popitem() function is used to remove the last item from a specified dictionary. For example:

x = {"Date": "02", "Day": "Thu", "Month": "Dec", "Year": "2021"}
print(x)

x.popitem()
print(x)

The output will be:

{'Date': '02', 'Day': 'Thu', 'Month': 'Dec', 'Year': '2021'}
{'Date': '02', 'Day': 'Thu', 'Month': 'Dec'}

Note - If you heard about popitem(), that it removes an item from a specified dictionary, randomly, instead of the last one. Then let me tell you, yes it was true, but before the Python Version 3.7.

Python popitem() Function Syntax

The syntax of popitem() function in Python, is:

dictionaryName.popitem()

It returns the removed item.

Python popitem() Function Syntax

Here is an example of popitem() in Python:

x = {"Date": "02", "Day": "Thu", "Month": "Dec", "Year": "2021"}
print(x)

print("\nThe item that is going to remove is:", x.popitem())
print("\nNow the dictionary is:")
print(x)

The snapshot given below shows the sample output produced by this Python program, demonstrating the popitem() function:

python popitem function

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋