Remove Key/Value Pairs from a Dictionary
In Python, you can remove key/value pairs from a dictionary using several methods. Below are examples demonstrating different approaches.
Example 1: Using del to Remove a Key/Value Pair
# Define a dictionary
test_dict = {"Runoob": 1, "Google": 2, "Taobao": 3, "Zhihu": 4}
# Print original dictionary
print("Dictionary before removal: " + str(test_dict))
# Use 'del' to remove the key 'Zhihu'
del test_dict['Zhihu']
# Print dictionary after removal
print("Dictionary after removal: " + str(test_dict))
# Trying to delete a non-existent key will raise an error
# del test_dict['Baidu'] # Uncommenting this line will raise a KeyErrorOutput:
Dictionary before removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
Dictionary after removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3}Example 2: Using pop() to Remove a Key/Value Pair
# Define a dictionary
test_dict = {"Runoob": 1, "Google": 2, "Taobao": 3, "Zhihu": 4}
# Print original dictionary
print("Dictionary before removal: " + str(test_dict))
# Use 'pop()' to remove the key 'Zhihu'
removed_value = test_dict.pop('Zhihu')
# Print dictionary after removal
print("Dictionary after removal: " + str(test_dict))
print("Removed value for key 'Zhihu': " + str(removed_value))
print('
')
# Use 'pop()' with a custom message for a non-existent key
removed_value = test_dict.pop('Baidu', 'Key not found')
# Print dictionary after attempting to remove a non-existent key
print("Dictionary after removal: " + str(test_dict))
print("Removed value: " + str(removed_value))Output:
Dictionary before removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
Dictionary after removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3}
Removed value for key 'Zhihu': 4
Dictionary after removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3}
Removed value: Key not foundExample 3: Using items() to Remove a Key/Value Pair
# Define a dictionary
test_dict = {"Runoob": 1, "Google": 2, "Taobao": 3, "Zhihu": 4}
# Print original dictionary
print("Dictionary before removal: " + str(test_dict))
# Use dictionary comprehension to remove the key 'Zhihu'
new_dict = {key: val for key, val in test_dict.items() if key != 'Zhihu'}
# Print dictionary after removal
print("Dictionary after removal: " + str(new_dict))Output:
Dictionary before removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
Dictionary after removal: {'Runoob': 1, 'Google': 2, 'Taobao': 3}These examples show how to remove key/value pairs from a dictionary using different methods in Python.