Sometimes, we want to remove a key from a Python dictionary.
In this article, we’ll look at how to remove a key from a Python dictionary.
How to remove a key from a Python dictionary?
To remove a key from a Python dictionary, we can use the dict’s pop method.
For instance, we write
my_dict.pop('key', None)
to call pop with the key of the dict to remove and the default value to return if the entry with 'key' isn’t found in the list.
This works no matter if an entry with key 'key' is in my_dict or not.
If the key exists for sure, we can use del
del my_dict['key']
to remove the entry with key 'key' from my_dict.
Conclusion
To remove a key from a Python dictionary, we can use the dict’s pop method.