简体   繁体   English

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

[英]sort a dictionary within another dictionary

I want to Sort the dictionary by score. 我想按分数对字典排序。 if the score is same then sort them by name 如果分数相同,则按名称排序

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

Help plz Thanks. 帮助请谢谢。

I think this should work... 我认为这应该有效...

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

It works by comparing tuples (score,name). 它通过比较元组(分数,名称)来工作。 Tuple comparison looks at the first item -- if those are the same, it looks at the second item and so forth. 元组比较着眼于第一项-如果相同,则着眼于第二项,依此类推。 So, (55,'jack') > (54,'lemon) and (55,'j') < (55,'k'). 因此,(55,'jack')>(54,'lemon)和(55,'j')<(55,'k')。

Of course, this returns the keys of yourdict in the order desired -- there's no way to actually sort a dictionary since dictionaries have no concept of order. 当然,这yourdict所需的顺序返回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))

returns: 返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM