2014-11-23 52 views
2

我試圖輸出對應於該最高值的寵物的名字:對字典進行排序並輸出對應於最高值的密鑰?

import operator 
pets = {"Dog":3, "Cat":5, "Rabbit":0} 
sorted_pets = sorted(pets.items(), key=operator.itemgetter(1), reverse = True) 
print (sorted_pets[0]) 

上面的代碼輸出['Cat', 5]。我怎樣才能改變它,所以它只輸出Cat

謝謝。

回答

7

可能是一個更Python的選擇:

>>> max(pets, key=pets.get) 
'Cat' 
+0

哇,這是一個更方便的方法。謝謝! – Oceanescence 2014-11-23 15:42:56

0
sorted_pets[0][0] 

試試這個。這個應該這樣做。

+0

謝謝!我怎麼想那個?很簡單! – Oceanescence 2014-11-23 15:29:16

+0

@Oceanescence歡迎:) – vks 2014-11-23 15:31:32

相關問題