popitem() function in dictionary in python by R4R Team

- popitem() is a python dictionary function which are able to pop(delete) the top most item of the dictionary.

Syntax-

dict.popitem()

- here popitem() takes no argument, by default it delete top most item.

Example-

dictionary is d={1:1,2:2,3:3}
d.popitem() will return {1:1,2:2} // it remove 3:3 from the dictionary.


program-

d={1:"one",2:"two",3:"Three",4:"Four"}
print(d)
d.popitem()
print(d)
d.popitem()
print(d)
d.popitem()
print(d)
d.popitem()
print(d)


output-

{1: 'one', 2: 'two', 3: 'Three', 4: 'Four'}
{1: 'one', 2: 'two', 3: 'Three'}
{1: 'one', 2: 'two'}
{1: 'one'}
{}


-if we try to pop items from the empty dictionary like

program-

d={}
d.popitem()
print(d)


output-

d.popitem()
KeyError: 'popitem(): dictionary is empty'


-if we try to pass argument in the popitem() function like-

program-

d={1:"one",2:"two",3:"Three",4:"Four"}
print(d)
d.popitem(4)


output-

d.popitem(4)
TypeError: popitem() takes no arguments (1 given)


-Hence we popitem() function take no argument and can't apply on empty dictionary.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!