Python 根据值从字典中删除条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15158599/
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-18 13:29:45  来源:igfitidea点击:

Removing entries from a dictionary based on values

python

提问by OneMoreError

I have a dictionary with character-integer key-value pair. I want to remove all those key value pairs where the value is 0.

我有一本带有字符整数键值对的字典。我想删除所有值为 0 的键值对。

For example:

例如:

>>> hand
{'a': 0, 'i': 0, 'm': 1, 'l': 1, 'q': 0, 'u': 0}

I want to reduce the same dictionary to this:

我想将同一个字典减少到这个:

>>> hand
{'m': 1, 'l': 1}

Is there an easy way to do that?

有没有简单的方法来做到这一点?

采纳答案by Niklas B.

You can use a dict comprehension:

您可以使用字典理解

>>> { k:v for k, v in hand.items() if v }
{'m': 1, 'l': 1}

Or, in pre-2.7 Python, the dictconstructor in combination with a generator expression:

或者,在 2.7 之前的 Python 中,dict构造函数与生成器表达式结合使用:

>>> dict((k, v) for k, v in hand.iteritems() if v)
{'m': 1, 'l': 1}

回答by Pavel Anossov

A dict comprehension?

字典理解?

{k: v for k, v in hand.items() if v != 0}

In python 2.6 and earlier:

在 python 2.6 及更早版本中:

dict((k, v) for k, v in hand.items() if v != 0)

回答by Volatility

hand = {k: v for k, v in hand.iteritems() if v != 0}

For Pre-Python 2.7:

对于 Python 2.7 之前的版本:

hand = dict((k, v) for k, v in hand.iteritems() if v != 0)

In both cases you're filtering out the keys whose values are 0, and assigning handto the new dictionary.

在这两种情况下,您都将过滤掉值为0, 并分配hand给新字典的键。

回答by Fabian

If you don't want to create a new dictionary, you can use this:

如果你不想创建一个新字典,你可以使用这个:

>>> hand = {'a': 0, 'i': 0, 'm': 1, 'l': 1, 'q': 0, 'u': 0}
>>> for key in list(hand.keys()):  ## creates a list of all keys
...     if hand[key] == 0:
...             del hand[key]
... 
>>> hand
{'m': 1, 'l': 1}
>>>