本文翻译自:How to remove a key from a Python dictionary?
When deleting a key from a dictionary, I use: 从字典中删除键时,我使用:
if 'key' in myDict:
del myDict['key']
Is there a one line way of doing this? 有没有一种方法可以做到这一点?
#1楼
参考:https://stackoom.com/question/lJm4/如何从Python字典中删除键
#2楼
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop() : 要删除键而不管它是否在字典中,请使用dict.pop()的两个参数形式:
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. 这将返回my_dict[key]如果key在字典中存在,并None其他。 If the second parameter is not specified (ie. my_dict.pop('key') ) and key does not exist, a KeyError is raised. 如果未指定所述第二参数(即my_dict.pop('key')和key不存在,一个KeyError上升。
To delete a key that is guaranteed to exist, you can also use 要删除肯定存在的密钥,您还可以使用
del my_dict['key']
This raises a KeyError if the key does not exist in the dictionary. 如果字典中不存在键,则会引发KeyError 。
#3楼
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 . 但是,您应该考虑从dict删除对象的这种方式不是原子的 -在'key' if语句中'key'可能位于myDict中,但是可能在执行del之前被删除,在这种情况下del将失败并返回KeyError 。 Given this, it would be safest to either use dict.pop or something along the lines of 鉴于此, 使用dict.pop或类似以下内容将是最安全的
try:
del myDict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner. 当然,这绝对不是单线的。
#4楼
It took me some time to figure out what exactly my_dict.pop("key", None) is doing. 我花了一些时间弄清楚my_dict.pop("key", None)到底在做什么。 So I'll add this as an answer to save others Googling time: 因此,我将其添加为答案以节省其他Google搜索时间:
pop(key[, default])If key is in the dictionary, remove it and return its value, else return default . 如果key在字典中,请删除它并返回其值,否则返回default 。 If default is not given and key is not in the dictionary, a
KeyErroris raised. 如果默认是没有给出关键不是在字典中,一个KeyError升高。
#5楼
If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable: 如果您需要在一行代码中从字典中删除很多键,我认为使用map()非常简洁且Python可读:
myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}
And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this: 并且,如果您需要在弹出字典中没有的值的地方捕获错误,请在map()中使用lambda,如下所示:
map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}
or in python3 , you must use a list comprehension instead: 或在python3 ,必须改为使用列表python3 :
[myDict.pop(x, None) for x in ['a', 'c', 'e']]
It works. 有用。 And 'e' did not cause an error, even though myDict did not have an 'e' key. 即使myDict没有“ e”键,“ e”也不会引起错误。
#6楼
Use: 采用:
>>> if myDict.get(key): myDict.pop(key)
Another way: 其他方式:
>>> {k:v for k, v in myDict.items() if k != 'key'}
You can delete by conditions. 您可以按条件删除。 No error if key doesn't exist. 如果key不存在,则没有错误。
本文详细介绍了在Python中从字典删除键的多种方法,包括使用del语句、dict.pop()函数及其区别,同时提供了代码示例和注意事项。
2219

被折叠的 条评论
为什么被折叠?



