What Is List Popitem() In Dictionary Python-Kaizensk

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:

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. 

 



Source link