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?
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']
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With