在Python中,字典按值排序,但仅返回键 [英] in Python, dictionary sort by value, but only return key
本文介绍了在Python中,字典按值排序,但仅返回键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Python 3.3.1(新手)
Im using Python 3.3.1 (newbie)
我有一个带有整数键和整数值的字典 我需要对这本字典进行排序,并返回值低于阈值(例如"t")的键列表
I have a dictionary with a integer key and integer value I need to sort this dictionary and return a list of key where the value falls below a threshold (say 't')
到目前为止,我有
list_integer = sorted(dict_int_int.items(), key=lambda x: x[1] )
这将按值对字典进行排序-到目前为止一切都很好,但是如何将值限制在't'以下,然后仅返回键
this sorts the dictionary by value -- everything is fine so far, but how do I limit the values to be below 't' and then ONLY return the keys
预先感谢
推荐答案
尝试一下:
[key for key,value in sorted(dic.items() ,key=lambda x : x[1]) if value < threshold]
或使用operator.itemgetter
:
>>> from operator import itemgetter
>>> [key for key,value in sorted(dic.items() ,key= itemgetter(1) ) if value < threshold]
这篇关于在Python中,字典按值排序,但仅返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文