Method Name:
popitem
Method Signature:
popitem()
Method Overview:
- The method popitem() removes a key-value pair from a dictionary instance and returns it.
- An item is removed in LIFO(Last In First Out) fashion.
Parameters:
None
Return Value:
The removed key-value pair as a tuple.
Exception Handling:
When the dictionary is empty, invoking the popitem() raises a KeyError.
Example 1:
# Example Python program that removes removed = musicalchairs.popitem(); print("After removing %s:%s"%(removed, musicalchairs)); print("After removing %s:%s"%(removed, musicalchairs)); |
Output:
Initial state: |
Example 2:
# Example Python program that removes # Create a dictionary print("Number of racks:"); # Remove all the items print("Number of racks after shop close:"); |
Output:
Number of racks: 5 Number of racks after shop close: 0 |