The popitem() method removes and returns the last item in the dictionary.

The syntax is as shown below:

Syntax:
d.popitem()

The method does not take any argument. It returns a two-length tuple in the form of (key, value) of the removed item.

ExampleEdit & Run
d = {'Moscow': 'Russia',
      'Delhi': 'India',
      'Manilla': 'Philippines',
      'Nairobi': 'Kenya'
    }

#remove random items
print(d.popitem())
print(d.popitem())

#the remaining
print(d)
Output:
('Nairobi', 'Kenya') ('Manilla', 'Philippines') {'Moscow': 'Russia', 'Delhi': 'India'} [Finished in 0.012699438999902668s]

If the dictionary is empty, a KeyError exception will be raised.

ExampleEdit & Run
d = {'Moscow': 'Russia', 
      'Delhi': 'India', 
    }

#remove random items
print(d.popitem())
print(d.popitem())
print(d.popitem()) #raises a KeyError
Output:
('Delhi', 'India') ('Moscow', 'Russia') KeyError: 'popitem(): dictionary is empty' [Finished in 0.012670318999994379s]