簡體   English   中英

獲取字典中最小值對應的key

[英]Get the key corresponding to the minimum value within a dictionary

如果我有 Python 字典,如何獲取包含最小值的條目的鍵?

我正在考慮與min()函數有關的事情...

鑒於輸入:

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

它將返回321

最佳: min(d, key=d.get) -- 沒有理由插入無用的lambda間接層或提取項目或鍵!

>>> d = {320: 1, 321: 0, 322: 3}
>>> min(d, key=d.get)
321

這是一個實際上給出了 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()會更有效。

對於具有相同最小值的多個鍵,您可以使用列表理解:

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]

等效的功能版本:

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

對於您有多個最小鍵並希望保持簡單的情況

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']

編輯:這是 OP 關於最小鍵的原始問題的答案,而不是最小答案。


您可以使用keys函數獲取字典的keys ,並且使用min查找該列表的最小值是正確的。

如果您不確定是否沒有多個最小值,我建議:

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
"""

解決具有相同最小值的多個鍵的問題的另一種方法:

>>> 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]

min與迭代器一起使用(對於 python 3,使用items而不是iteritems ); 而不是 lambda 使用來自運算符的itemgetter ,它比 lambda 快。

from operator import itemgetter
min_key, _ = min(d.iteritems(), key=itemgetter(1))

我比較了以下三個選項的表現:

    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 )

示例輸出:

#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]

要創建一個可排序的類,您必須覆蓋 6 個特殊函數,以便 min() 函數調用它

這些方法是__lt__ , __le__, __gt__, __ge__, __eq__ , __ne__ ,它們的順序是小於、小於或等於、大於、大於或等於、等於、不等於。 例如你應該實現__lt__如下:

def __lt__(self, other):
  return self.comparable_value < other.comparable_value

那么您可以按如下方式使用 min 函數:

minValue = min(yourList, key=(lambda k: yourList[k]))

這對我有用。

min(zip(d.values(), d.keys()))[1]

使用 zip 函數創建包含值和鍵的元組迭代器。 然后用 min 函數包裝它,該函數根據第一個鍵取最小值。 這將返回一個包含 (value, 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

這是你想要的?

d = dict()
d[15.0]='fifteen'
d[14.0]='fourteen'
d[14.5]='fourteenandhalf'

print d[min(d.keys())]

打印“十四”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM