How to return smallest value in dictionary?

2020-07-09 10:09发布

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?

7条回答
乱世女痞
2楼-- · 2020-07-09 10:48

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

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

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

查看更多
Ridiculous、
3楼-- · 2020-07-09 10:50

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)

查看更多
太酷不给撩
4楼-- · 2020-07-09 10:53
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
查看更多
小情绪 Triste *
5楼-- · 2020-07-09 11:10

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

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']
查看更多
倾城 Initia
6楼-- · 2020-07-09 11:10

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)
查看更多
兄弟一词,经得起流年.
7楼-- · 2020-07-09 11:13
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 transform to 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.

查看更多
登录 后发表回答