在python中按值删除字典项的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29218750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:13:45  来源:igfitidea点击:

What is the best way to remove a dictionary item by value in python?

pythonpython-2.7python-3.xdictionary

提问by elegent

I wonder if there is simpleway to remove oneor moredictionary element(s) from a python dictionary by value.

我想知道是否有一种简单的方法可以按值从 python 字典中删除一个多个字典元素。

We have a dictionary called myDict:

我们有一本字典叫做myDict

myDict = {1:"egg", "Answer":42, 8:14, "foo":42}

and want to removeall items which valuesare equal to 42.

并且想要删除等于 的所有项目42

Implementation suggestion:

实施建议:

  1. Get a list of all keys of a certain value in myDict
    (See for instance get key by value in dictionary.)

  2. Delete this dict element or elements (based on the found keys) from myDict
    (For more information, see Delete an element from a dictionary.)

  1. 获取特定值的所有键的列表myDict
    (参见例如在字典中按值获取键。)

  2. Delete this dict element or elements (based based on the found keys) from myDict
    (有关更多信息,请参阅从字典中删除元素。)

So, what do you think now is the most elegantand most “pythonic”way to implement this problem in Python?

那么,你认为现在用 Python 实现这个问题的最优雅最“pythonic”的方式是什么?

采纳答案by A.J. Uppal

You can use a simple dictcomprehension:

你可以使用一个简单的dict理解:

myDict = {key:val for key, val in myDict.items() if val != 42}

As such:

像这样:

>>> {key:val for key, val in myDict.items() if val != 42}
{8: 14, 1: 'egg'}

回答by cruane

You must create a copy to iterate over as changing the size of the dictionary inside of a loop causes a RunTimeError. Iterate over key, value pairs in your dictionary copy using items() and compare each value to the value you are looking for. If they match, delete the key from the dictionary.

您必须创建一个副本以进行迭代,因为在循环内更改字典的大小会导致 RunTimeError。使用 items() 迭代字典副本中的键值对,并将每个值与您要查找的值进行比较。如果它们匹配,则从字典中删除该键。

    for key, value in dict(myDict).items():
        if value == 42:
            del mydict[key]

Adding answer for question in the comments below as it was too big for a comment. Here is a quick console session showing that mydict.copy()and dict(myDict)accomplish the same thing.

在下面的评论中添加问题的答案,因为评论太大了。这是一个快速控制台会话,显示mydict.copy()dict(myDict)完成相同的事情。

>>>import copy
>>>dict1 = {1:"egg", "Answer":42, 8:14, "foo":42}
>>>dict2 = dict(dict1)
>>>dict3 = dict1.copy()
>>>dict4 = dict1
>>>dict1[1] = "egg sandwich"
>>>dict1
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict2
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict3
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict4
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict2['foo'] = "I pity the"
dict1
>>>{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict2
{'Answer': 42, 1: 'egg', 'foo': 'I pity the', 8: 14}
>>>dict3
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict4
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict4[8] = "new"
>>>dict1
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 'new'}
>>>dict2
{'Answer': 42, 1: 'egg', 'foo': 'I pity the', 8: 14}
>>>dict3
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict4
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 'new'}
`

回答by kasper Taeymans

Use a dictionary comprehension.

使用字典理解。

if you need a copy use iteritems()

如果您需要复印使用 iteritems()

>>> {k:v for k, v in myDict.iteritems() if v!=42}
{8: 14, 1: 'egg'}

if you don't need a copy of your dictionary you can use viewitems()

如果你不需要你的字典副本,你可以使用 viewitems()

>>> {k:v for k, v in myDict.viewitems() if v!=42}
{8: 14, 1: 'egg'}

回答by Padraic Cunningham

You can iterate over a copy and do a lookup:

您可以遍历副本并进行查找:

for k in myDict.copy():
    if myDict[k] == 42:
        del myDict[k]

Or only copy the keys:

或者只复制密钥:

myDict = {1:"egg", "Answer":42, 8:14, "foo":42}
for k in list(myDict):
    if myDict[k] == 42:
        del myDict[k]
print(myDict)
{8: 14, 1: 'egg'}

Which if you want to mutate the original dict should be the most efficient.

如果你想改变原始 dict 应该是最有效的。

回答by NevDev

I like following a "hit list" approach where you iterate through the dictionary, then add the ones you want to delete to a list, then after iterating, delete the entries from that list like so:

我喜欢遵循“命中列表”方法,在其中遍历字典,然后将要删除的内容添加到列表中,然后在迭代后,从该列表中删除条目,如下所示:

hitList =[] for dictEntry: if test condition, hitList.append

hitList =[] for dictEntry: 如果是测试条件,hitList.append

for entry in hitList: delete dict[entry]

对于命中列表中的条目:删除 dict[entry]

this is just some pseudocode but i've been successful with this in the past

这只是一些伪代码,但我过去在这方面取得了成功