To find the minimum value in a Python dictionary you can use the min() built-in function applied to the result of the dictionary values() method.
How to find min and max value in dictionary Python. In Python to find the minimum and maximum values in a dictionary, we can use the built-in min() and max() functions. In Python the max() function is used to find the maximum values in a given dictionary.
Best: min(d, key=d.get)
-- no reason to interpose a useless lambda
indirection layer or extract items or keys!
>>> d = {320: 1, 321: 0, 322: 3}
>>> min(d, key=d.get)
321
Here's an answer that actually gives the solution the OP asked for:
>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1])
(321, 0)
Using d.iteritems()
will be more efficient for larger dictionaries, however.
For multiple keys which have equal lowest value, you can use a list comprehension:
d = {320:1, 321:0, 322:3, 323:0}
minval = min(d.values())
res = [k for k, v in d.items() if v==minval]
[321, 323]
An equivalent functional version:
res = list(filter(lambda x: d[x]==minval, d))
min(d.items(), key=lambda x: x[1])[0]
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