How to remove a key from a python dictionary?
When trying to delete a key from a dictionary, I write:
if 'key' in myDict:
del myDict['key']
Is there a one line way of doing this?
Use 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 (ie. my_dict.pop('key')
) and key
does not exist, a KeyError
is raised.
Specifically to answer "is there a one line way of doing this?"
if 'key' in myDict: del myDict['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 myDict
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 myDict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
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 KeyError is raised
Documentation
链接地址: http://www.djcxy.com/p/2902.html上一篇: JavaScript查询字符串
下一篇: 如何从Python字典中删除密钥?