根据值从字典中删除条目 [英] Removing entries from a dictionary based on values
本文介绍了根据值从字典中删除条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一本带有字符-整数键-值对的字典.我想删除所有值为 0 的键值对.
例如:
<预><代码>>>>手{'a':0,'i':0,'m':1,'l':1,'q':0,'u':0}我想把同一个字典简化成这样:
<预><代码>>>>手{'m':1,'l':1}有没有简单的方法可以做到这一点?
解决方案
您可以使用 字典理解:
<预><代码>>>>{ k:v for k, v in hand.items() if v }{'m':1,'l':1}或者,在 2.7 之前的 Python 中,dict
构造函数结合 生成器表达式:
I have a dictionary with character-integer key-value pair. I want to remove all those key value pairs where the value is 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:
>>> { 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:
>>> dict((k, v) for k, v in hand.iteritems() if v)
{'m': 1, 'l': 1}
这篇关于根据值从字典中删除条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文