Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 986
Alexa Elis Avatar asked Apr 19 '13 07:04

Alexa Elis


3 Answers

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']
like image 188
Jon Clements Avatar answered Sep 21 '22 23:09

Jon Clements


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)

like image 31
6502 Avatar answered Sep 18 '22 23:09

6502


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)
like image 27
Artsiom Rudzenka Avatar answered Sep 19 '22 23:09

Artsiom Rudzenka