如何返回字典中的最小值? [英] How to return smallest value in dictionary?

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

问题描述

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

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"]

因为绿色和红色的值都最小.

because green and red has both the least value.

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

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天全站免登陆