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

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

How to return smallest value in dictionary?

pythondictionary

提问by Alexa Elis

Let say I have a dictionary of total of fruits:

假设我有一本关于水果总数的字典:

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

And I want the output to be

我希望输出是

["pineapple"]

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

因为菠萝的价值最低。或者如果我有这个:

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

The output will be:

输出将是:

["green","red"]

because green and red has both the least value.

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

So how do I return the smallest value in dictionary?

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

采纳答案by Jon Clements

Can do it as a two-pass:

可以做两遍:

>>> 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. Find the min value of the dict's values
  2. Then go back over and extract the key where it's that value...
  1. 找到字典值的最小值
  2. 然后返回并提取该值所在的键...

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):

另一种选择(需要一些导入,这意味着如果需要,您可以使用 n 个)-此代码仅使用第一个(这将是最小值):

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

回答by Artsiom Rudzenka

Just an option:

只是一个选择:

from collections import defaultdict
from operator import itemgetter

Fruits = {"apple":8, "banana":3, "lemon":5, "pineapple":2,}
Colour = {"blue":5, "green":2, "purple":6, "red":2}


def get_res(dVals):
    res = defaultdict(list)
    for k, v in dVals.items():
        res[v].append(k)
    return min(res.items(), key=itemgetter(0))[1]

print get_res(Fruits)
print get_res(Colour)

回答by 6502

I would say that the best option is to make two passes:

我会说最好的选择是进行两次传球:

min_value = min(dict.values())
result = [key for key, value in dict.iteritems() if value == min_value]

You can make a single pass by looping explicitly:

您可以通过显式循环进行单次传递:

result = []
min_value = None
for key, value in dict.iteritems():
    if min_value is None or value < min_value:
        min_value = value
        result = []
    if value == min_value:
        result.append(key)

but this is going to be slower (except may be in PyPy)

但这会变慢(除了可能在 PyPy 中)

回答by 7stud

colors = {"blue":5, "green":2, "purple":6, "red":2}# {"apple":8, "banana":3, "lemon":5, "pineapple":2,}

sorted_items = sorted(colors.items(), key=lambda t: t[1])
print (sorted_items)


min_val = sorted_items[0][1]

for t in sorted_items:
    if t[1] == min_val:
        print(t[0])
    else:
        break




--output:--
[('green', 2), ('red', 2), ('blue', 5), ('purple', 6)]

green
red

回答by Snakes and Coffee

import itertools
def getmin(dictionary):
    gen = ((j,i) for i,j in dictionary.iteritems())
    items = sorted(gen)
    minimum = items.pop(0)
    rest = itertools.takewhile(lambda item:item[0]==minimum[0],items)
    return [x[1] for x in itertools.chain([minimum],rest)]

This method uses a schwartzian transformto take advantage of native sorting (no key required). It sorts the items based on the value of the key in the dictionary, takes the minimum, and takes all of the ones that are the same.

此方法使用施瓦兹变换来利用本机排序(不需要密钥)。它根据字典中键的值对项目进行排序,取最小值,并取所有相同的项。

回答by Nemokosch

As I see, it works with a dirty lambda function like this:

正如我所见,它与一个像这样的脏 lambda 函数一起工作:

`min(Fruits,key=lambda x:Fruits[x]).`

I guess it will return only one value but still quite nice. :)

我想它只会返回一个值,但仍然很不错。:)

回答by niksy

minimum = []      # creates empty list for all possible minimum keys
def min(dict):    # defines a function called minimum taking a argument dict
    m= min(dict.values())     # stating minimum value in dict
    for key, values in dict.items():     # iterating through key and values in items of dictionary
        if value == m:        # checking if value is minimum
            minimum.append(key)      # appending minimum values to the empty list created
    return minimum         # returning the list