2015-12-06 123 views
0

打印具有相同值的多個字典密鑰,因此可以說我有一個包含不同密鑰的多個最大值的字典。我試圖使用代碼:如何使用max()函數

taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1} 
    print(max(taste, key=taste.get)) 

但它只給我貽貝或貝特,這取決於哪一個先來。我試圖設置的最高值,然後通過我的鑰匙,併爲每個鍵重複,我的價值觀如:

highest = max(taste.values()) 
    for i in taste.keys(): 
     for j in taste[i]: 
     if j == highest: 
      print(i) 

但似乎沒有工作,因爲你無法通過像在我的字典中的值的整數interate 。那麼最乾淨和最簡單的方法是做什麼

+0

你想要什麼作爲輸出'[[「Mussel s「],[Limpets]]或其中任何一個以任意(隨機)順序? – ZdaR

+2

你只想'如果味道[我] ==最高',當然? – jonrsharpe

回答

0

你可以使用列表解析。

>>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1} 
>>> highest = max(taste.values()) 
>>> [k for k, v in taste.items() if v == highest] 
['Limpets', 'Mussels'] 

>>> for i in taste.keys(): 
...  if taste[i] == highest: 
...   print(i) 
... 
Limpets 
Mussels 
0

因爲你已經是最大的集多個值,你需要在一個位聰明的你是如何篩選出所有具有相同值的鍵。

這是更多的排序操作,而不是最大操作。

>>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1} 
>>> ordered_by_rating = sorted(list(taste.items()), key=lambda x: x[1], reverse=True) 
>>> top_rating = max(ordered_by_rating, key=lambda x: x[1])[1] 
>>> only_top = [x[0] for x in filter(lambda x: x[1] == top_rating, ordered_by_rating)] 
>>> only_top 
['Mussels', 'Limpets'] 

您可以壓縮以上,通過降低循環的數量,你必須要經過:

>>> [k for k,v in taste.items() if v == max(taste.values())] 
['Mussels', 'Limpets'] 
1

這是我會做什麼:

highest_value = max(taste.itervalues()) 
print [key for key, value in taste.iteritems() if value == highest_value] 
0

該解決方案是使用Python3:

maxkeys = [k for k, v in taste.items() if v == max(taste.values())]