辞書をスコアで並べ替えたい。スコアが同じ場合は、名前で並べ替えます
{
'sudha' : {score : 75}
'Amruta' : {score : 95}
'Ramesh' : {score : 56}
'Shashi' : {score : 78}
'Manoj' : {score : 69}
'Resham' : {score : 95}
}
助けてくださいありがとう。
辞書をスコアで並べ替えたい。スコアが同じ場合は、名前で並べ替えます
{
'sudha' : {score : 75}
'Amruta' : {score : 95}
'Ramesh' : {score : 56}
'Shashi' : {score : 78}
'Manoj' : {score : 69}
'Resham' : {score : 95}
}
助けてくださいありがとう。
私はこれがうまくいくはずだと思う...
sorted(yourdict,key=lambda x:(yourdict[x]['score'],x))
タプル(スコア、名前)を比較することで機能します。タプルの比較では、最初の項目が調べられます。それらが同じ場合は、2 番目の項目が調べられます。したがって、(55,'jack') > (54,'lemon) および (55,'j') < (55,'k') です。
もちろん、これはyourdict
目的の順序で のキーを返します。辞書には順序の概念がないため、辞書を実際にソートする方法はありません。
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']