Step-by-Step Guide to Deleting a Key-Value Pair from a Dictionary
To delete a key-value pair from a Python dictionary, you can use the del
statement or the pop()
method. Here are five examples showing how to do this:
- Using the
del
statement:
# Example 1
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['a']
print(my_dict) # Output: {'b': 2, 'c': 3}
- Using the
pop()
method:
# Example 2
my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_value = my_dict.pop('b')
print(removed_value) # Output: 2
print(my_dict) # Output: {'a': 1, 'c': 3}
- Removing a non-existent key using
del
:
# Example 3
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['d'] # KeyError: 'd'
- Removing a non-existent key using
pop()
:
# Example 4
my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_value = my_dict.pop('d', 'Key not found')
print(removed_value) # Output: Key not found
- Removing and retrieving a key-value pair using
pop()
with default value:
# Example 5
my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_value = my_dict.pop('d', 'Key not found')
print(removed_value) # Output: Key not found
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
These examples demonstrate how to remove key-value pairs from a dictionary using both del
and pop()
methods, and also handle cases where the key may not exist in the dictionary.