The Pop Method Of Python Dictionary Class

Method Name:

pop

Method Signature:

pop(key[, default])

Overview:

  • Given a key, the method removes the corresponding key-value pair from a Python dictionary and returns the pair as a tuple.

  • If the key is not found in the dictionary the method raises a KeyError.

Parameters:

key - The value for which the key-value pair is to be removed

default - An optional default value which is to be returned, if the key is not found. If this default value is not provided and the key is not found in the dictionary, a KeyError is raised.

Return Value:

If the key is found, a tuple containing the key-value pair corresponding to the key.

Exceptions:

KeyError if the key is not found and the default value parameter is not specified.

Example:

# Example Python program that pops
# key-value pairs correpondonding to specific keys, from a dictionary

# Create an empty dictionary
polygon = dict();

# Add points to the polygon
polygon["p1"] = (20, 40);
polygon["p2"] = (80, 40);
polygon["p3"] = (20, 60);
polygon["p4"] = (80, 60);
polygon["p5"] = (50, 20);

print("Points in the polygon:");
for point in polygon:
    print("%s : %s"%(point, polygon[point]));

print("Number of points in the polygon:");    
print(len(polygon));

pointRemoved = polygon.pop("p5");
print("Removed the point using pop():");
print(pointRemoved);

print("Points in the polygon after a pop():");
for point in polygon:
    print("%s : %s"%(point, polygon[point]));

print("Number of points in the polygon after a pop():");    
print(len(polygon));

Output:

Points in the polygon:
p1 : (20, 40)
p2 : (80, 40)
p3 : (20, 60)
p4 : (80, 60)
p5 : (50, 20)
Number of points in the polygon:
5
Removed the point using pop():
(50, 20)
Points in the polygon after a pop():
p1 : (20, 40)
p2 : (80, 40)
p3 : (20, 60)
p4 : (80, 60)
Number of points in the polygon after a pop():
4

Copyright 2023 © pythontic.com