Python Dictionary - PopItem

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
# key-value pairs from a python dictionary
musicalchairs = {1:"Participant1",
                2:"Participant2",
                3:"Participant3"};
print("Initial state:");
print(musicalchairs);
print("--");

removed = musicalchairs.popitem();

print("After removing %s:%s"%(removed, musicalchairs));
print("--");
removed = musicalchairs.popitem();

print("After removing %s:%s"%(removed, musicalchairs));
print("--");
print(type(removed));

Output:

Initial state:
{1: 'Participant1', 2: 'Participant2', 3: 'Participant3'}
--
After removing (3, 'Participant3'):{1: 'Participant1', 2: 'Participant2'}
--
After removing (2, 'Participant2'):{1: 'Participant1'}
--
<class 'tuple'>

Example 2:

# Example Python program that removes
# key-value pairs from a dictionary instance
# using popitem

# Create a dictionary
backeryView = {"Rack 1": "Cakes",
                "Rack 2": "Cookies",
                "Rack 3": "Croissant",
                "Rack 4": "Tarts",
                "Rack 5": "Baguette"};

print("Number of racks:");                
print(len(backeryView));

# Remove all the items
while len(backeryView):
    backeryView.popitem();

print("Number of racks after shop close:");                
print(len(backeryView));

Output:

Number of racks:
5
Number of racks after shop close:
0

Copyright 2023 © pythontic.com