简体   繁体   English

根据值从字典中删除条目

[英]Removing entries from a dictionary based on values

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? 有一个简单的方法吗?

You can use a dict comprehension : 你可以使用dict理解

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

Or, in pre-2.7 Python, the dict constructor 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}
hand = {k: v for k, v in hand.iteritems() if v != 0}

For Pre-Python 2.7: 对于Pre-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 hand to the new dictionary. 在这两种情况下,您都会过滤出值为0的键,并将hand指定给新词典。

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM