You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中比较字典值并输出所有最大值对应键的代码修正

How to Get All Keys with the Maximum Value

Got it, let's figure out why your current code only returns dog and how to adjust it to get both dog;cat.

First, a quick note: avoid using dict as a variable name since it's a built-in Python type—it can cause confusion later on. I renamed it to my_dict in the fixed code below.

Why your original code returns only "dog"

Your line biggestKey = max([[dict[key],key] for key in dict])[1] creates a list of [value, key] pairs. When max() compares these pairs, it first checks the value (the first element). When values are equal (both 5 for "dog" and "cat"), it then compares the keys lexicographically. Since "dog" comes before "cat" in dictionary order, max() picks that pair, leaving you with only "dog".

Fixed Code

Here's how to collect all keys that have the maximum value, then join them with semicolons:

my_dict = {"hello" : 3, "dog" : 5, "cat" : 5, "fish" : 1}
# Grab the highest value present in the dictionary
max_value = max(my_dict.values())
# Collect every key that matches the maximum value
max_keys = [key for key, val in my_dict.items() if val == max_value]
# Join the keys into a single string separated by semicolons
print(';'.join(max_keys))

Breakdown of the fix:

  1. max(my_dict.values()) gets the highest value in the dictionary (which is 5 here)
  2. The list comprehension loops through every key-value pair and keeps only the keys tied for the maximum value
  3. ';'.join(max_keys) converts the list of keys into a single string formatted exactly how you want

Running this code will output: dog;cat

内容的提问来源于stack exchange,提问作者Daniel Tinchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:15:23