如何从Python字典中删除键?

问题:如何从Python字典中删除键?

从字典中删除键时,我使用:

if 'key' in my_dict:
    del my_dict['key']

有没有一种方法可以做到这一点?

When deleting a key from a dictionary, I use:

if 'key' in my_dict:
    del my_dict['key']

Is there a one line way of doing this?


回答 0

要删除键而不管它是否在字典中,请使用以下两个参数的形式dict.pop()

my_dict.pop('key', None)

my_dict[key]如果key字典中存在,则返回,None否则返回。如果第二个参数未指定(即my_dict.pop('key'))并且key不存在,KeyError则引发a。

要删除肯定存在的密钥,您还可以使用

del my_dict['key']

KeyError如果密钥不在字典中,则将引发a 。

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 (ie. 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.


回答 1

专门回答“是否有一种统一的方法?”

if 'key' in my_dict: del my_dict['key']

…嗯,你问过 ;-)

你应该考虑,虽然,从删除对象的这种方式dict不是原子 -它是可能的,'key'可能是在my_dict该过程中if的语句,但是可以删除之前del被执行,在这种情况下del将失败,KeyError。鉴于此,最安全的使用dict.pop方式是

try:
    del my_dict['key']
except KeyError:
    pass

当然,这绝对不是单线的。

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.


回答 2

我花了一些时间弄清楚究竟my_dict.pop("key", None)在做什么。因此,我将其添加为答案以节省其他Google搜索时间:

pop(key[, default])

如果key在字典中,请删除它并返回其值,否则返回default。如果未提供默认值并且字典中没有KeyError则引发a。

文献资料

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


回答 3

del my_dict[key]my_dict.pop(key)在键存在时从字典中删除键要快一些

>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"

>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786

但是,当密钥不存在时,它会if key in my_dict: del my_dict[key]比稍快一点my_dict.pop(key, None)。两者都至少比快三倍deltry/ except语句:

>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
...     del d['missing key']
... except KeyError:
...     pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133

del my_dict[key] is slightly faster than my_dict.pop(key) for removing a key from a dictionary when the key exists

>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"

>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786

But when the key doesn’t exist if key in my_dict: del my_dict[key] is slightly faster than my_dict.pop(key, None). Both are at least three times faster than del in a try/except statement:

>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
...     del d['missing key']
... except KeyError:
...     pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133

回答 4

如果您需要在一行代码中从字典中删除很多键,我认为使用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}

并且,如果您需要在弹出字典中没有的值的地方捕获错误,请在map()中使用lambda,如下所示:

map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}

或中的python3,您必须改为使用列表推导:

[myDict.pop(x, None) for x in ['a', 'c', 'e']]

有用。即使myDict没有“ e”键,“ e”也不会引起错误。

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:

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 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:

[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.


回答 5

您可以使用字典理解来创建新字典,并删除该键:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

您可以按条件删除。如果key不存在,则没有错误。

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.


回答 6

使用“ del”关键字:

del dict[key]

Using the “del” keyword:

del dict[key]

回答 7

我们可以通过以下几种方法从Python字典中删除键。

使用del关键字;这几乎与您所采用的方法相同-

 myDict = {'one': 100, 'two': 200, 'three': 300 }
 print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
 if myDict.get('one') : del myDict['one']
 print(myDict)  # {'two': 200, 'three': 300}

要么

我们可以像下面这样:

但是请记住,在此过程中,它实际上不会从字典中删除任何键,而不会从该字典中排除特定的键。另外,我观察到它返回的字典与的顺序不同myDict

myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}

如果我们在外壳中运行它,它将执行类似的操作{'five': 500, 'four': 400, 'three': 300, 'two': 200}-请注意,它与的顺序不同myDict。再次,如果我们尝试打印myDict,那么我们可以看到所有键,包括通过这种方法从字典中排除的键。但是,我们可以通过将以下语句分配给变量来创建新字典:

var = {key:value for key, value in myDict.items() if key != 'one'}

现在,如果我们尝试打印它,它将遵循父命令:

print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

要么

使用pop()方法。

myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)

if myDict.get('one') : myDict.pop('one')
print(myDict)  # {'two': 200, 'three': 300}

del和之间的区别在于pop,使用pop()方法,我们实际上可以根据需要存储键的值,如下所示:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100

如果您觉得有用,请叉要点以备将来参考。

We can delete a key from a Python dictionary by the some following approaches.

Using the del keyword; it’s almost the same approach like you did though –

 myDict = {'one': 100, 'two': 200, 'three': 300 }
 print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
 if myDict.get('one') : del myDict['one']
 print(myDict)  # {'two': 200, 'three': 300}

Or

We can do like following:

But one should keep in mind that, in this process actually it won’t delete any key from the dictionary rather than making specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.

myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}

If we run it in the shell, it’ll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} – notice that it’s not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

var = {key:value for key, value in myDict.items() if key != 'one'}

Now if we try to print it, then it’ll follow the parent order:

print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

Or

Using the pop() method.

myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)

if myDict.get('one') : myDict.pop('one')
print(myDict)  # {'two': 200, 'three': 300}

The difference between del and pop is that, using pop() method, we can actually store the key’s value if needed, like the following:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100

Fork this gist for future reference, if you find this useful.


回答 8

如果您想要非常冗长,可以使用异常处理:

try: 
    del dict[key]

except KeyError: pass

但是,pop()如果键不存在,这比方法要慢。

my_dict.pop('key', None)

几个键无关紧要,但是如果重复执行此操作,则后一种方法是更好的选择。

最快的方法是这样的:

if 'key' in dict: 
    del myDict['key']

但是此方法很危险,因为如果'key'在两行之间将其删除,KeyError则会引发a。

You can use exception handling if you want to be very verbose:

try: 
    del dict[key]

except KeyError: pass

This is slower, however, than the pop() method, if the key doesn’t exist.

my_dict.pop('key', None)

It won’t matter for a few keys, but if you’re doing this repeatedly, then the latter method is a better bet.

The fastest approach is this:

if 'key' in dict: 
    del myDict['key']

But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.


回答 9

我更喜欢不变的版本

foo = {
    1:1,
    2:2,
    3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
    return {
        k:v
        for k,v in dct.items() if k not in keyIter
    }

>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}

I prefer the immutable version

foo = {
    1:1,
    2:2,
    3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
    return {
        k:v
        for k,v in dct.items() if k not in keyIter
    }

>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}

回答 10

另一种方法是通过使用items()+ dict理解

items()结合dict理解也可以帮助我们完成键-值对删除的任务,但是它具有不适合就地使用dict的缺点。实际上,如果创建了一个新字典,除了我们不希望包含的密钥之外。

test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21} 

# Printing dictionary before removal 
print ("dictionary before performing remove is : " + str(test_dict)) 

# Using items() + dict comprehension to remove a dict. pair 
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'} 

# Printing dictionary after removal 
print ("dictionary after remove is : " + str(new_dict)) 

输出:

dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

Another way is by Using items() + dict comprehension

items() coupled with dict comprehension can also help us achieve task of key-value pair deletion but, it has drawback of not being an inplace dict technique. Actually a new dict if created except for the key we don’t wish to include.

test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21} 

# Printing dictionary before removal 
print ("dictionary before performing remove is : " + str(test_dict)) 

# Using items() + dict comprehension to remove a dict. pair 
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'} 

# Printing dictionary after removal 
print ("dictionary after remove is : " + str(new_dict)) 

Output:

dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

回答 11

单键过滤

  • 如果my_dict中存在“ key”,则返回“ key”并将其从my_dict中删除
  • 如果my_dict中不存在“键”,则返回None

这将改变my_dict(可变)

my_dict.pop('key', None)

按键上有多个过滤器

生成一个新的字典(不可变的)

dic1 = {
    "x":1,
    "y": 2,
    "z": 3
}

def func1(item):
    return  item[0]!= "x" and item[0] != "y"

print(
    dict(
        filter(
            lambda item: item[0] != "x" and item[0] != "y", 
            dic1.items()
            )
    )
)

Single filter on key

  • return “key” and remove it from my_dict if “key” exists in my_dict
  • return None if “key” doesn’t exist in my_dict

this will change my_dict in place (mutable)

my_dict.pop('key', None)

Multiple filters on keys

generate a new dict (immutable)

dic1 = {
    "x":1,
    "y": 2,
    "z": 3
}

def func1(item):
    return  item[0]!= "x" and item[0] != "y"

print(
    dict(
        filter(
            lambda item: item[0] != "x" and item[0] != "y", 
            dic1.items()
            )
    )
)