What is popitem() method in dictionary | How to use the popitem() method of the dictionary.

Definition:

This method simply removes the last inserted item from the dictionary, since it returns the item, we can print it directly or using any variable. The original dictionary gets changed.

Syntax:

X = dictionary.popitem()

This method takes no argument.

Working:

list_popitem_dictionary_python

popitem_output_list

Copy Code Here.

dictionary = {1: ‘Student’,
‘Name’: ‘Waqar Khan’,
‘Age’: 23,
‘Male’: True,
‘Subjects’: ‘Computers’}

x = dictionary.popitem()
print(x)
print(dictionary)

Code:

  1. A dictionary with some random values is being taken
  2. popitem() method is being applied to the dictionary. And its returned value is printed inside x.
  3. After removing the item, the original dictionary is printed.

Output:

  1. The last inserted item is removed
  2. The original dictionary was changed.

Interview questions:

  • How will you remove the desired item from the dictionary using the popitem() method?

We cannot do it using the popitem() method as it returns the last inserted item, but we can remove the desired item from the dictionary using pop() method. 

 

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

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