snippetpythonCritical
How can I remove a key from a Python dictionary?
Viewed 0 times
howkeypythonremovecandictionaryfrom
Problem
I want to remove a key from a dictionary if it is present. I currently use this code:
Without the
See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).
if key in my_dict:
del my_dict[key]
Without the
if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).
Solution
To delete a key regardless of whether it is in the dictionary, use the two-argument form of
This will return
To delete a key that is guaranteed to exist, you can also use
This will raise a
dict.pop():my_dict.pop('key', None)
This will return
my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.To delete a key that is guaranteed to exist, you can also use
del my_dict['key']This will raise a
KeyError if the key is not in the dictionary.Code Snippets
del my_dict['key']Context
Stack Overflow Q#11277432, score: 4816
Revisions (0)
No revisions yet.