How to get the minimum value in a dictionary in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To get the minimum value in a Python dictionary, you can use the built-in min()
function, which works similarly to the max()
function. One way to use min()
with a dictionary is to call min()
on the dictionary’s values. Here’s an example:
my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
min_value = min(my_dict.values())
print(min_value) # Output: 10
In this example, min()
is called with my_dict.values()
as an argument, which returns a view object of the dictionary’s values. The resulting minimum value is stored in the min_value
variable and printed to the console.
If you want to get the key of the minimum value in the dictionary, you can use the key
argument in min()
to define a custom function that returns the value for each key-value pair. Here’s an example:
my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
min_key = min(my_dict, key=my_dict.get)
print(min_key) # Output: 'key1'
In this example, min()
is called on my_dict
with the key
argument set to my_dict.get
, which returns the value for each key-value pair. The resulting key with the minimum value is stored in the min_key
variable and printed to the console.
Note that these methods assume that the values in the dictionary are comparable elements. Otherwise, you may get a TypeError
if you try to compare non-comparable types such as strings and integers.