Python中比较字典值并输出所有最大值对应键的代码修正
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:
max(my_dict.values())gets the highest value in the dictionary (which is 5 here)- The list comprehension loops through every key-value pair and keeps only the keys tied for the maximum value
';'.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

