How can I remove a key from a Python dictionary?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Melt
--
Chapters
00:00 Question
00:22 Accepted answer (Score 4356)
01:01 Answer 2 (Score 452)
01:50 Answer 3 (Score 193)
02:21 Answer 4 (Score 80)
03:15 Thank you
--
Full question
https://stackoverflow.com/questions/1127...
Accepted answer links:
[dict.pop()]: http://docs.python.org/library/stdtypes....
Answer 2 links:
[not atomic]: https://stackoverflow.com/q/17326067/722...
[use ]: https://stackoverflow.com/a/11277439/722...
Answer 3 links:
[Documentation]: https://docs.python.org/2/library/stdtyp...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #unset
#avk47
ACCEPTED ANSWER
Score 4659
To delete a key regardless of whether it is in the dictionary, use the two-argument form of 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.
ANSWER 2
Score 470
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
ANSWER 3
Score 203
It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:
pop(key[, default])If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a
KeyErroris raised.
ANSWER 4
Score 71
You can use a dictionary comprehension to create a new dictionary with that key removed:
>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}
You can delete by conditions. No error if key doesn't exist.