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

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

Selecting elements of a Python dictionary greater than a certain value

pythondictionary

提问by Jesse O

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]

回答by Shashank

You want dict[i]not dict.values(). dict.values()will return the whole list of values that are in the dictionary.

你想dict[i]没有dict.values()dict.values()将返回字典中的整个值列表。

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

回答by nmaier

.items()will return (key, value)pairs that you can use to reconstruct a filtered dictusing a list comprehensionthat is feed into the dict()constructor, that will accept an iterable of (key, value)tuples aka. our list comprehension:

.items()将返回(key, value)对,你可以用它来重建过滤dict使用列表理解,进料到的dict()构造,将接受一个可迭代的(key, value)元组又名。我们的列表理解:

>>> 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 answerusing "dict comprehensions":

如果您不关心在 2.7 版之前的 Python 上运行您的代码,请参阅使用“dict comprehensions”的@opatut 回答

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

回答by opatut

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. I found this by googling "python dictionary list comprehension", top post.

在这里找到:Create a dictionary with list comprehension in Python。我通过谷歌搜索“python 字典列表理解”找到了这个,顶帖。

Explanation

解释

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