Python中如何打印字典最小值对应的键?
Hey there! Let's break down what's going on here and fix your issue.
First, let's look at the code you already have:
my_dict = {'x':500, 'y':5874, 'z': 560} key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print('Minimum Value: ',my_dict[key_min])
The thing you might not realize is that key_min is already the key you're looking for! The min() function here uses the key parameter to compare the values of the dictionary, and returns the corresponding key that has the smallest value.
So to print the key for the minimum value, you don't need to mess around with my_dict.keys() at all—just print key_min directly:
print('Key for Minimum Value:', key_min)
When you run this, you'll get the output: Key for Minimum Value: x, which is exactly what you want.
Why your original attempt didn't work
- In Python 3,
my_dict.keys()returns adict_keysobject, not a list. This object doesn't support indexing with[key_min](since it's not a sequence with positional indexes). - Even if it were a list,
key_minis the actual key (like'x'), not a numeric index position—so using it to "index" the keys would throw an error anyway.
A small simplification
You can even shorten your min() call a bit, since iterating directly over a dictionary loops through its keys by default. So this works the same way:
key_min = min(my_dict, key=lambda k: my_dict[k])
内容的提问来源于stack exchange,提问作者sara jones

