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

Python中如何打印字典最小值对应的键?

How to Print the Key Corresponding to the Minimum Value in a Dictionary

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 a dict_keys object, 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_min is 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:41:12