AppDividend
Latest Code Tutorials

Python Dictionary popitem() Function Example

0

Python dictionary popitem() is an inbuilt method that is used to remove an arbitrary element from a dictionary. It will remove the key and value, means an item from the dictionary. The popitem() is an inbuilt method that removes the item that was last inserted into the dictionary. In Python 3.7 before, the popitem() method removes the random item. The removed item is the return value of a popitem() method.

Python Dictionary popitem()

Python popitem() is a method of dictionary, which doesn’t take any parameter and removes and returns the arbitrary (key, value) pair as a 2-tuple. If the popitem() is applied on an empty dictionary, a KeyError will be raised.

Syntax

dict_name.popitem()

The dictionary popitem() method does not take any element. Here, dict_name is the name of the dictionary.

Return Value

The popitem() method returns an arbitrary element (key and value) pair from the dictionary, and it removes that pair from the dictionary. The popitem() method returns a KeyError if the dictionary is empty.

Programming Example

# app.py

# Declaring a dictionary
dict1 = {'Flower': 'Rose', 'Fruit': 'Apple',
         'Bird': 'Parrot', 'Animal': 'Tiger'}
# printing the dictionary
print(dict1)
# Now we will call popitem() to remove an arbitary item
# popped item will be stored in item
item = dict1.popitem()
# Printing popped item
print(item)
# printing the new dictionary
print("After pop new dictionary is: ")
print(dict1)

Output

{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot', 'Animal': 'Tiger'}
('Animal', 'Tiger')
After pop new dictionary is:
{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}

In this example, we can see that we have declared one dictionary, and then we have printed the dictionary.

After that, we have called the popitem() method to remove one arbitrary element from the dictionary, and then we have stored it in the variable named item. After that, we have printed items and a new dictionary.

The popitem() method in the dictionary helps to achieve a similar purpose. It removes the arbitrary key-value pair from the dictionary and returns it as a tuple.

Python popitem dictionary function removes the last inserted key-value pair and prints the removed items.

See also

Python dictionary items()

Python dictionary fromKeys()

Python dictionary keys()

Leave A Reply

Your email address will not be published.

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