[英]Get the key corresponding to the minimum value within a dictionary
If I have a Python dictionary, how do I get the key to the entry which contains the minimum value?如果我有 Python 字典,如何获取包含最小值的条目的键?
I was thinking about something to do with the min()
function...我正在考虑与
min()
函数有关的事情...
Given the input:鉴于输入:
{320:1, 321:0, 322:3}
It would return 321
.它将返回
321
。
Best: min(d, key=d.get)
-- no reason to interpose a useless lambda
indirection layer or extract items or keys!最佳:
min(d, key=d.get)
-- 没有理由插入无用的lambda
间接层或提取项目或键!
>>> d = {320: 1, 321: 0, 322: 3}
>>> min(d, key=d.get)
321
Here's an answer that actually gives the solution the OP asked for:这是一个实际上给出了 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)
Using d.iteritems()
will be more efficient for larger dictionaries, however.但是,对于较大的字典,使用
d.iteritems()
会更有效。
For multiple keys which have equal lowest value, you can use a list comprehension:对于具有相同最小值的多个键,您可以使用列表理解:
d = {320:1, 321:0, 322:3, 323:0}
minval = min(d.values())
res = [k for k, v in d.items() if v==minval]
[321, 323]
An equivalent functional version:等效的功能版本:
res = list(filter(lambda x: d[x]==minval, d))
min(d.items(), key=lambda x: x[1])[0]
>>> d = {320:1, 321:0, 322:3}
>>> min(d, key=lambda k: d[k])
321
For the case where you have multiple minimal keys and want to keep it simple对于您有多个最小键并希望保持简单的情况
def minimums(some_dict):
positions = [] # output variable
min_value = float("inf")
for k, v in some_dict.items():
if v == min_value:
positions.append(k)
if v < min_value:
min_value = v
positions = [] # output variable
positions.append(k)
return positions
minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})
['e', 'c']
Edit: this is an answer to the OP's original question about the minimal key, not the minimal answer.编辑:这是 OP 关于最小键的原始问题的答案,而不是最小答案。
You can get the keys of the dict using the keys
function, and you're right about using min
to find the minimum of that list.您可以使用
keys
函数获取字典的keys
,并且使用min
查找该列表的最小值是正确的。
If you are not sure that you have not multiple minimum values, I would suggest:如果您不确定是否没有多个最小值,我建议:
d = {320:1, 321:0, 322:3, 323:0}
print ', '.join(str(key) for min_value in (min(d.values()),) for key in d if d[key]==min_value)
"""Output:
321, 323
"""
Another approach to addressing the issue of multiple keys with the same min value:解决具有相同最小值的多个键的问题的另一种方法:
>>> dd = {320:1, 321:0, 322:3, 323:0}
>>>
>>> from itertools import groupby
>>> from operator import itemgetter
>>>
>>> print [v for k,v in groupby(sorted((v,k) for k,v in dd.iteritems()), key=itemgetter(0)).next()[1]]
[321, 323]
Use min
with an iterator (for python 3 use items
instead of iteritems
);将
min
与迭代器一起使用(对于 python 3,使用items
而不是iteritems
); instead of lambda use the itemgetter
from operator, which is faster than lambda.而不是 lambda 使用来自运算符的
itemgetter
,它比 lambda 快。
from operator import itemgetter
min_key, _ = min(d.iteritems(), key=itemgetter(1))
I compared how the following three options perform:我比较了以下三个选项的表现:
import random, datetime
myDict = {}
for i in range( 10000000 ):
myDict[ i ] = random.randint( 0, 10000000 )
# OPTION 1
start = datetime.datetime.now()
sorted = []
for i in myDict:
sorted.append( ( i, myDict[ i ] ) )
sorted.sort( key = lambda x: x[1] )
print( sorted[0][0] )
end = datetime.datetime.now()
print( end - start )
# OPTION 2
start = datetime.datetime.now()
myDict_values = list( myDict.values() )
myDict_keys = list( myDict.keys() )
min_value = min( myDict_values )
print( myDict_keys[ myDict_values.index( min_value ) ] )
end = datetime.datetime.now()
print( end - start )
# OPTION 3
start = datetime.datetime.now()
print( min( myDict, key=myDict.get ) )
end = datetime.datetime.now()
print( end - start )
Sample output:示例输出:
#option 1
236230
0:00:14.136808
#option 2
236230
0:00:00.458026
#option 3
236230
0:00:00.824048
d={}
d[320]=1
d[321]=0
d[322]=3
value = min(d.values())
for k in d.keys():
if d[k] == value:
print k,d[k]
to create an orderable class you have to override 6 special functions, so that it would be called by the min() function要创建一个可排序的类,您必须覆盖 6 个特殊函数,以便 min() 函数调用它
these methods are __lt__ , __le__, __gt__, __ge__, __eq__ , __ne__
in order they are less than, less than or equal, greater than, greater than or equal, equal, not equal.这些方法是
__lt__ , __le__, __gt__, __ge__, __eq__ , __ne__
,它们的顺序是小于、小于或等于、大于、大于或等于、等于、不等于。 for example you should implement __lt__
as follows:例如你应该实现
__lt__
如下:
def __lt__(self, other):
return self.comparable_value < other.comparable_value
then you can use the min function as follows:那么您可以按如下方式使用 min 函数:
minValue = min(yourList, key=(lambda k: yourList[k]))
this worked for me.这对我有用。
min(zip(d.values(), d.keys()))[1]
Use the zip function to create an iterator of tuples containing values and keys.使用 zip 函数创建包含值和键的元组迭代器。 Then wrap it with a min function which takes the minimum based on the first key.
然后用 min 函数包装它,该函数根据第一个键取最小值。 This returns a tuple containing (value, key) pair.
这将返回一个包含 (value, key) 对的元组。 The index of [1] is used to get the corresponding key
[1]的索引用于获取对应的key
# python
d={320:1, 321:0, 322:3}
reduce(lambda x,y: x if d[x]<=d[y] else y, d.iterkeys())
321
Is this what you are looking for?这是你想要的?
d = dict()
d[15.0]='fifteen'
d[14.0]='fourteen'
d[14.5]='fourteenandhalf'
print d[min(d.keys())]
Prints 'fourteen'打印“十四”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.