If popitem() is used with an empty dictionary what happens?

(a) an empty dictionary is returned

(b) an empty tuple is returned

(c) trace back error is raised

(d) keyerror is raised

 

Answer:

  • The popitem() method is used to remove and return a random key-value pair from a dictionary object in Python. 
  • The popitem() method takes no arguments and returns a tuple containing the removed key and value. For example, if mydict = {‘a’: 23, ‘b’: ‘78’, ‘d’: 36}, then mydict.popitem() could return (‘b’, ‘78’) or (‘d’, 36) or (‘a’, 23), depending on the random selection. The method also modifies the dictionary object in place, so the removed key-value pair is no longer present in the dictionary.
  • However, if the dictionary object is empty, meaning it has no key-value pairs, then the popitem() method cannot remove or return anything. In this case, the method raises a KeyError exception, that indicates that the requested key is not found in the dictionary. For example, if mydict = {}, then mydict.popitem() will raise a KeyError: ‘popitem(): dictionary is empty’ error.

So, the correct answer is (d) keyerror is raised .

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo