How to Remove a Key From a Dictionary in Python
What are some ways we can remove a key from a dictionary?
Using del
If we know the key exists for sure, we can run del
.
del some_dict['key']
If the key doesn’t exist, this will return a KeyError
.
We can circumvent this issue with a try except
.
try:
del some_dict['key']
except KeyError:
pass
Using pop()
If we don’t know whether the key exists or need the deleted value, we can use pop()
.
This will default the return value to None
if the key doesn’t exist.
deleted_value = some_dict.pop('key', None)
Compared to del
with the try except
, pop()
is a good deal faster when the key doesn’t exist since raising an exception is quite slow.
On the other hand, del
with the try except
is marginally faster when a key exists.