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?
As I see, it works with a dirty lambda function like this:
I guess it will return only one value but still quite nice. :)
I would say that the best option is to make two passes:
You can make a single pass by looping explicitly:
but this is going to be slower (except may be in PyPy)
Can do it as a two-pass:
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):
Just an option:
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.