Appearance
How can I remove a key from a Python dictionary?
You can use the del statement to remove a key-value pair from a dictionary in Python. Here is an example:
Remove a key from a Python dictionary using a del statement
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']
print(my_dict) # {'a': 1, 'c': 3}
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
Alternatively, you can use the pop() method to remove a key-value pair from the dictionary and return the value. This is useful if you want to retrieve the value before deleting the key. Here is an example:
Remove a key from a Python dictionary using pop method
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print(value) # 2
print(my_dict) # {'a': 1, 'c': 3}The pop() method also takes an optional second argument, which is the default value to return if the key is not found in the dictionary. This can be useful to avoid KeyError exceptions.
Remove a key from a Python dictionary using pop method along with a default value
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('d', 'not found')
print(value) # 'not found'
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}