How to get the keys with the lowest value in a dictionary in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To get the key or keys with the lowest value in a dictionary in Python, you can use the min() function along with the key parameter set to dict.get().

Here’s an example:

my_dict = {'A': 3, 'B': 4, 'H': 1, 'K': -2, 'T': 0}

key_with_min_value = min(my_dict, key=my_dict.get)

print(key_with_min_value) # 'K'

This will print the key K, which has the lowest value (-2) in the dictionary.

If you want to get all the keys with the lowest value (in case of a tie), you can iterate over the dictionary and collect all the keys with the same minimum value in a list:

my_dict = {'A': 3, 'B': 4, 'H': -2, 'K': -2, 'T': 0}

min_value = min(my_dict.values())
keys_with_min_value = [k for k, v in my_dict.items() if v == min_value]

print(keys_with_min_value) # ['H', 'K']

In this case, since there are two keys (H and K) with the minimum value (-2), the list will contain both of them.

Tags: