How to delete a key from a dictionary in Python
Learn how you can remove a key from a dictionary in Python.
This article shows how you can remove a key from a dictionary in Python.
To delete a key, you can use two options:
- Using
del my_dict['key']
- Using
my_dict.pop('key', None)
Let's look at both options in detail:
#more
Using del
¶
The first option is to use the del
keyword:
data = {'a': 1, 'b': 2}
del data['a']
# data: {'b': 2}
This will raise a KeyError
if the key does not exist:
data = {'a': 1, 'b': 2}
del data['c']
# KeyError: 'c'
So you can wrap it either in a if
statement or a try-except
block to avoid an Exception:
if 'c' in data:
del data['c']
# or
try:
del data['c']
except KeyError:
pass
Using pop()
¶
The second option is to use the pop(key[, default]) method.
If key
is in the dictionary, it removes it and returns its value, else it returns default
. If default
is not given and the key is not in the dictionary, a KeyError
is raised.
So if you use pop()
with None
as the default, it removes the key but doesn't raise a KeyError if the key does not exist.
data = {'a': 1, 'b': 2}
data.pop('a', None)
# data: {'b': 2}
data.pop('a', None)
# data: {'b': 2}
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*