深度阅读

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

作者
作者
2023年08月22日
更新时间
8.92 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。