在另一个字典中排序字典

时间:2012-05-23 13:34:48

标签: python

我想按分数对字典进行排序。如果得分相同,则按名称对其进行排序

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

帮助PLZ 感谢。

2 个答案:

答案 0 :(得分:6)

我认为这应该有用......

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

它通过比较元组(得分,名称)来工作。元组比较查看第一项 - 如果它们是相同的,它会查看第二项,依此类推。所以,(55,' jack')> (54,'柠檬)和(55,' j')< (55' K&#39)。

当然,这会按照所需的顺序返回yourdict的键 - 由于字典没有顺序概念,因此无法对字典进行实际排序。

答案 1 :(得分: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']
相关问题