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 # Create an empty dictionary # Add points to the polygon print("Points in the polygon:"); print("Number of points in the polygon:"); pointRemoved = polygon.pop("p5"); print("Points in the polygon after a pop():"); print("Number of points in the polygon after a pop():"); |
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 |