如何返回对应于字典中最小值的键列表 [英] How to return a list of keys corresponding to the smallest value in dictionary

查看:115
本文介绍了如何返回对应于字典中最小值的键列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说一本关于水果总数的字典:

Let say I have a dictionary of total of fruits:

Fruits = {"apple":8, "banana":3, "lemon":5, "pineapple":2,}

我希望输出为

["pineapple"]

菠萝的价值最小。或者,如果我有这个:

because pineapple has the least value. Or if I have this:

Colour = {"blue":5, "green":2, "purple":6, "red":2}

输出将是:

["green","red"]

因为绿色和红色都具有

那么如何返回字典中的最小值?

So how do I return the smallest value in dictionary?

推荐答案

可以通过两次通过:

>>> colour
{'blue': 5, 'purple': 6, 'green': 2, 'red': 2}
>>> min_val = min(colour.itervalues())
>>> [k for k, v in colour.iteritems() if v == min_val]
['green', 'red']




  1. 找到字典值的最小值

  2. 然后返回并提取该值所在的键。 。

另一种方法(需要一些导入,如果需要,您可以选择n个)-该代码只需要第一个(这将是最小值):

An alternative (requires some imports, and means you could take the n many if wanted) - this code just takes the first though (which would be the min value):

from itertools import groupby
from operator import itemgetter

ordered = sorted(colour.iteritems(), key=itemgetter(1))
bykey = groupby(ordered, key=itemgetter(1))
print map(itemgetter(0), next(bykey)[1])
# ['green', 'red']

这篇关于如何返回对应于字典中最小值的键列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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