获取对应于字典中最小值的键

如果我有Python字典,如何获得包含最小值的条目的键?


我正在考虑与该min()功能有关的事情...


给定输入:


{320:1, 321:0, 322:3}

它将返回321。


30秒到达战场
浏览 883回答 3
3回答

MMTTMM

这实际上是提供OP所需解决方案的答案:>>> d = {320:1, 321:0, 322:3}>>> d.items()[(320, 1), (321, 0), (322, 3)]>>> # find the minimum by comparing the second element of each tuple>>> min(d.items(), key=lambda x: x[1]) (321, 0)d.iteritems()但是,对于较大的词典,使用将更为有效。

浮云间

对于您有多个最小键并希望保持简单的情况def minimums(some_dict):&nbsp; &nbsp; positions = [] # output variable&nbsp; &nbsp; min_value = float("inf")&nbsp; &nbsp; for k, v in some_dict.items():&nbsp; &nbsp; &nbsp; &nbsp; if v == min_value:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; positions.append(k)&nbsp; &nbsp; &nbsp; &nbsp; if v < min_value:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; min_value = v&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; positions = [] # output variable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; positions.append(k)&nbsp; &nbsp; return positionsminimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})['e', 'c']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python