在另一本词典中对词典排序

2024-09-30 02:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按分数把字典分类。如果分数相同,则按名称排序

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

帮助plz 谢谢。你知道吗


Tags: 名称字典排序分类分数scoreplzramesh
2条回答
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']

我想这应该管用。。。你知道吗

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

它通过比较元组(score,name)来工作。元组比较查看第一个项目如果它们相同,则查看第二个项目,依此类推。所以,(55,'jack')>;(54,'lemon)和(55,'j')<;(55,'k')。你知道吗

当然,这会按所需的顺序返回yourdict的键,因为字典没有顺序的概念,所以无法对字典进行实际排序。你知道吗

相关问题 更多 >

    热门问题