选择大于某个值的Python字典的元素 [英] Selecting elements of a Python dictionary greater than a certain value

查看:2869
本文介绍了选择大于某个值的Python字典的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要选择某个值或更大的字典元素。我知道如何使用列表, 返回列表中的项目列表大于某个值

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()将返回(key,value)您可以使用 dict 在 <$中添加rel =noreferrer>列表解析 c $ c> dict()构造函数,它将接受(key,value)元组的迭代。我们的列表理解:

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

不要在Python 2.7以上的python上运行代码,请参阅 @opatut answer ,使用dict comprehensions

If you don't care about running your code on python older than version 2.7, see @opatut answer using "dict comprehensions":

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

这篇关于选择大于某个值的Python字典的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆