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 pop
method.
For instance, we write:
my_dict = {'foo': 'abc', 'bar': 2}
deleted = my_dict.pop('foo', None)
print(deleted)
print(my_dict)
We call pop
with key of the item to delete and the fallback value of the entry that’s deleted if the entry with the key doesn’t exist.
Therefore, deleted
is 'abc'
.
And my_dict
is {'bar': 2}
after pop
is called.
If the key exists for sure in the dictionary, we can also use the del
operator.
For instance, we write:
my_dict = {'foo': 'abc', 'bar': 2}
del my_dict['foo']
print(my_dict)
Then we get the same result for my_dict
.
Conclusion
To remove a key from a Python dictionary, we can use the pop
method.
If the key exists for sure in the dictionary, we can also use the del
operator.