Python dictionary Method - popitem()
The popitem()
method is a dictionary method in Python that removes and returns an arbitrary (key, value)
pair from the dictionary. It can be used to remove and retrieve items from a dictionary in a single step.
The syntax for using popitem()
is as follows:
dict.popitem()Source:w.wwtheitroad.com
The method does not take any arguments, and it returns a tuple containing the key and value of the item that was removed.
If the dictionary is empty, calling popitem()
raises a KeyError
exception.
Here is an example that demonstrates the use of popitem()
:
>>> d = {'a': 1, 'b': 2, 'c': 3} >>> key, value = d.popitem() >>> print(key, value) 'c' 3 >>> print(d) {'a': 1, 'b': 2}
In this example, popitem()
is used to remove an arbitrary item from the dictionary d
. The key and value of the removed item are returned and assigned to the variables key
and value
, respectively. The resulting dictionary d
contains only the remaining items.