How to return a list of keys corresponding to the smallest value in dictionary
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']
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)