How to get the keys with the highest value in a dictionary in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To get the key or keys with the highest value in a dictionary in Python, you can use the max()
function along with the key
parameter set to dict.get()
.
Here’s an example:
my_dict = {'A': 3, 'B': 4, 'H': 1, 'K': 8, 'T': 0}
key_with_max_value = max(my_dict, key=my_dict.get)
print(key_with_max_value) # 'K'
This will print the key K
, which has the highest value (8
) in the dictionary.
If you want to get all the keys with the highest value (in case of a tie), you can iterate over the dictionary and collect all the keys with the same maximum value in a list:
my_dict = {'A': 3, 'B': 4, 'H': 1, 'K': 8, 'T': 0}
max_value = max(my_dict.values())
keys_with_max_value = [k for k, v in my_dict.items() if v == max_value]
print(keys_with_max_value) # ['K']
In this case, since there is only one key with the maximum value, the list will contain only K
.