- 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)
{1: 'one', 2: 'two', 3: 'Three', 4: 'Four'}
{1: 'one', 2: 'two', 3: 'Three'}
{1: 'one', 2: 'two'}
{1: 'one'}
{}
d={}
d.popitem()
print(d)
d.popitem()
KeyError: 'popitem(): dictionary is empty'
d={1:"one",2:"two",3:"Three",4:"Four"}
print(d)
d.popitem(4)
d.popitem(4)
TypeError: popitem() takes no arguments (1 given)