Reputation: 168
Sort the dictionary by score. if the score is same then sort them by name
import operator
dt={
'sudha' : {'score' : 75} ,
'Amruta' : {'score' : 95} ,
'Ramesh' : {'score' : 56} ,
'Shashi' : {'score' : 78} ,
'Manoj' : {'score' : 69} ,
'Resham' : {'score' : 95}
}
sorted_x1 = sorted(dt.items(), key=operator.itemgetter(1))
print sorted_x1
output is :
[('Ramesh', {'score': 56}), ('Manoj', {'score': 69}),
('sudha', {'score': 75}),
('Shashi', {'score': 78}), ('Resham', {'score': 95}), ('Amruta',{'score': 95})]
Now I want to Sort Last two elements by its name because its scores are same .
Upvotes: 2
Views: 107
Reputation: 304355
Careful, your code is actually comparing the dicts themselves rather than the scores. ie
{'score': 56} < {'score': 69}
May cause surprises if there are extra keys in the dictionaries. You can arrange the key
func to return a tuple
of the score
and the key
.
sorted_x1 = sorted(dt.items(), key=lambda (k, v): (v['score'], k))
If someone needs to do this in Python3, you will have to avoid the tuple unpacking in the lambda
as that is no longer allowed.
sorted_x1 = sorted(dt.items(), key=lambda k_v: (k_v[1]['score'], k_v[0]))
Upvotes: 5
Reputation: 6581
This is one way to do it:
k = sorted(dt, key=dt.__getitem__)
v = sorted(dt.values())
sorted_dt_scores = zip(k,v)
output when you print sorted_dt_scores
:
[('Ramesh', {'score': 56}), ('Manoj', {'score': 69}), ('sudha', {'score': 75}), ('Shashi', {'score': 78}), ('Resham', {'score': 95}), ('Amruta', {'score': 95})]
Upvotes: 1
Reputation: 90979
You can send the elements you want to sort on as a tuple or list, and sort will happen first on the first element, if first elements are same it will move on to the next element.
Example -
>>> dt={
... 'sudha' : {'score' : 75} ,
... 'Amruta' : {'score' : 95} ,
... 'Ramesh' : {'score' : 56} ,
... 'Shashi' : {'score' : 78} ,
... 'Manoj' : {'score' : 69} ,
... 'Resham' : {'score' : 95}
... }
>>>
>>> sorted_x1 = sorted(dt.items(), key=lambda x: (x[1]['score'], x[0]))
>>> sorted_x1
[('Ramesh', {'score': 56}), ('Manoj', {'score': 69}), ('sudha', {'score': 75}), ('Shashi', {'score': 78}), ('Amruta', {'score': 95}), ('Resham', {'score': 95})]
Upvotes: 3