2012-05-23 102 views
0

我想按分數對詞典進行排序。如果分數相同,則通過名稱在另一個詞典中對詞典進行排序

{ 
'sudha' : {score : 75} 
'Amruta' : {score : 95} 
'Ramesh' : {score : 56} 
'Shashi' : {score : 78} 
'Manoj' : {score : 69} 
'Resham' : {score : 95} 
} 

幫助PLZ 由於對它們進行排序。

+2

爲什麼不只是名字和分數,e.g的字典,'{ '蘇哈':75, 'Amruta':95}'? – Akavall

回答

6

我認爲這應該工作...

sorted(yourdict,key=lambda x:(yourdict[x]['score'],x)) 

它的工作原理,通過比較元組(得分,名稱)。元組比較查看第一個項目 - 如果它們相同,則查看第二個項目等等。所以,(55,'jack')>(54,'檸檬)和(55,'j')<(55,'k')。

當然,這會按照所需順序返回yourdict的鍵 - 由於字典沒有順序概念,因此無法對字典進行實際排序。

+0

謝謝你的男人。這工作。 – HussainNagri

4
d = { 
'sudha' : {'score' : 75}, 
'Amruta' : {'score' : 95}, 
'Ramesh' : {'score' : 56}, 
'Shashi' : {'score' : 78}, 
'Manoj' : {'score' : 69}, 
'Resham' : {'score' : 95}, 
} 

sorted(d, key=lambda x: (d[x]['score'], x)) 

回報:有

['Ramesh', 'Manoj', 'sudha', 'Shashi', 'Amruta', 'Resham'] 
+2

哇 - 完全一樣的答案。我們必須做些什麼... – mgilson

+0

感謝@eumiro它的工作。 – HussainNagri