Dictionary popitem() method Python

The Python dictionary popitem() method can be used if you wish to remove a random item(key value pair) from the dictionary.This method does not accept any argument.

 
>>> d={23:67 , 90:78 , 835:'New'}
>>> d.popitem()
(835, 'New')
>>> d
{23: 67, 90: 78}
>>> #Another example
>>> d1=dict( zip("Bias" , "Cheat"))
>>> d1
{'B': 'C', 'i': 'h', 'a': 'e', 's': 'a'}
>>> d1.popitem()
('s', 'a')
>>> d1
{'B': 'C', 'i': 'h', 'a': 'e'}

As you can see once popitem() is called and a random item removed it is no longer part of the dictionary.

There is a better method than popitem() which can remove a specific unwanted item from the dictionary,this method is known as pop().



Leave a Reply

Your email address will not be published. Required fields are marked *