Python - Dictionary Methods Part 3: Removing Data
These methods enable removing key-value pairs from dictionaries.
Methods and Examples
pop() Method Removes and returns the value for a specific key.
profession = my_dict.pop("profession")
print(profession) # Output: Engineer
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA', 'hobby': 'Reading'}
Explanation: pop() is ideal for retrieving and deleting a key in one step.
popitem() Method Removes and returns the last inserted key-value pair as a tuple.
last_item = my_dict.popitem()
print(last_item) # Output: ('hobby', 'Reading')
Explanation: Use popitem() for quick removal of the most recently added item.
clear() Method Empties the entire dictionary.
my_dict.clear()
print(my_dict) # Output: {}
Explanation: clear() is useful for resetting a dictionary.