2014-11-23 94 views
-1

的字典: -排序字典值 - 降我有字母

higharr = {'Alex':2, 
      'Steve':3, 
      'Andy':4, 
      'Wallace':6, 
      'Andy':3, 
      'Andy':5, 
      'Dan':1, 
      'Dan':0, 
      'Steve':3, 
      'Steve':8} 

for score in sorted(higharr.values(), reverse=True): 
    print (score) 

我想打印出與該值下降的字母順序是值的鍵。降序部分正在工作,但我不確定如何將相應的鍵添加到左側。

謝謝

+0

看看什麼higharr.keys()做什麼。然後排序該列表,並按照該順序詢問這些鍵的字典?...... – 2014-11-23 20:27:06

+2

您不能擁有這本詞典 - 您的鍵不是唯一的。嘗試打印higharr。你可能會發現你缺少條目。 – 2014-11-23 20:28:23

+0

你說「按字母順序降序」,但你正在按數值排序。你想要什麼命令? – iCodez 2014-11-23 20:29:19

回答

0

首先,有可能會有點混亂,以在你的字典哪些條目是「鑰匙」,哪些是「價值觀」。在Python中,字典由{key:value}通過鍵值對形成。因此,在higharr中,鍵是名稱,值是名稱權的整數。

正如其他人所說,higharr可能無法完全按照你期望的,因爲字典的鍵(名字)不是唯一的:

>>> higharr = {'Alex':2, 
       'Steve':3, 
       'Andy':4, 
       'Wallace':6, 
       'Andy':3, 
       'Andy':5, 
       'Dan':1, 
       'Dan':0, 
       'Steve':3, 
       'Steve':8} 

>>> higharr 
{'Steve': 8, 'Alex': 2, 'Wallace': 6, 'Andy': 5, 'Dan': 0} 

正如你所看到的,後來鍵值對你添加將覆蓋更早的。 話雖這麼說,您可以排序並打印在字典中對將作爲您以下要求所有獨特的鍵:

>>> for entry in sorted(higharr.items(), key = lambda x: x[1], reverse=True) 
...  print(entry) 
... 
('Steve', 8) 
('Wallace', 6) 
('Andy', 5) 
('Alex', 2) 
('Dan', 0) 

相反,如果你想通過降序字母順序排列的按鍵排序,你基本上可以做到同樣的事情:

>>> for entry in sorted(higharr.items(), key=lambda x: x[0], reverse=True): 
...  print(entry) 
... 
('Wallace', 6) 
('Steve', 8) 
('Dan', 0) 
('Andy', 5) 
('Alex', 2) 
+0

這真的有助於謝謝你 – baconstripsboss 2014-11-24 09:32:55

0

您可能會使用其他數據結構,因爲您有重複的鍵。 但總的來說,你可能會考慮這一點:

from operator import itemgetter 
for i in sorted(higharr.items(), key=itemgetter(1), reverse=True): 
    print i 
+0

非常好。乾杯 – baconstripsboss 2014-11-24 13:29:57

0

這是你在找什麼?

for key, score in sorted(higharr.values(), reverse=True): 
    print (key, score) 
+0

這也是工作。謝謝 – baconstripsboss 2014-11-24 13:30:20

0

你很近。枚舉字典的項目和使用自定義排序關鍵字:

>>> for name, score in sorted(higharr.iteritems(), key=lambda item:item[1], reverse=True): 
...  print name, score 
... 
Steve 8 
Wallace 6 
Andy 5 
Alex 2 
Dan 0 
>>> 
+0

優秀。謝謝 – baconstripsboss 2014-11-24 13:32:03