How to return a list of keys corresponding to the smallest value in dictionary

dictionary, python

Solution

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

- Find the min value of the dict's values

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

Problem

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?

Original source

Related problems