简体   繁体   English

选择大于某个值的Python字典元素

[英]Selecting elements of a Python dictionary greater than a certain value

I need to select elements of a dictionary of a certain value or greater. 我需要选择某个值或更大值的字典元素。 I am aware of how to do this with lists, Return list of items in list greater than some value . 我知道如何使用列表, 列表中的项目返回列表大于某个值

But I am not sure how to translate that into something functional for a dictionary. 但我不知道如何将其翻译成字典的功能。 I managed to get the tags that correspond (I think) to values greater than or equal to a number, but using the following gives only the tags: 我设法得到对应(我认为)大于或等于数字的值的标签,但使用以下仅给出标签:

[i for i in dict if dict.values() >= x]

.items() will return (key, value) pairs that you can use to reconstruct a filtered dict using a list comprehension that is feed into the dict() constructor , that will accept an iterable of (key, value) tuples aka. .items()将返回(key, value)对,您可以使用列表 .items()来重建已过滤的dict ,该列表 .items()被提供给dict()构造函数 ,它将接受一个(key, value)元组的迭代。 our list comprehension: 我们的列表理解:

>>> d = dict(a=1, b=10, c=30, d=2)
>>> d
{'a': 1, 'c': 30, 'b': 10, 'd': 2}
>>> d = dict((k, v) for k, v in d.items() if v >= 10)
>>> d
{'c': 30, 'b': 10}

If you don't care about running your code on python older than version 2.7, see @opatut answer using "dict comprehensions" : 如果您不关心在早于2.7版的python上运行代码,请参阅使用“dict comprehensions”的 @opatut answer

{k:v for (k,v) in dict.items() if v > something}

While nmaier's solution would have been my way to go, notice that since python 2.7+ there has been a " dict comprehension " syntax: 虽然nmaier的解决方案应该是我的方法,但请注意,因为python 2.7+有一个“ dict comprehension ”语法:

{k:v for (k,v) in dict.items() if v > something}

Found here: Create a dictionary with list comprehension in Python . 在这里找到: 在Python中创建一个包含列表推导的字典 I found this by googling "python dictionary list comprehension", top post. 我通过google搜索“python dictionary list comprehension”,顶部帖子找到了这个。

Explanation 说明

  • { .... } includes the dict comprehension { .... }包括词典理解
  • k:v what elements to add to the dict k:v要添加到dict的元素
  • for (k,v) in dict.items() this iterates over all tuples (key-value-pairs) of the dict for (k,v) in dict.items()这将遍历dict的所有元组(键值对)
  • if v > something a condition that has to apply on every value that is to be included if v > something条件必须适用于要包含的每个值

You want dict[i] not dict.values() . 你想要dict[i]不是dict.values() dict.values() will return the whole list of values that are in the dictionary. dict.values()将返回字典中的整个值列表。

dict = {2:5, 6:2}
x = 4
print [dict[i] for i in dict if dict[i] >= x] # prints [5]

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

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