sort dict or list by second value of the tuple and then by the first one

Viewed 459

I can't figure out why my code doesn't work, I have a list(or dict, i tried both) of tuples, I'd like to order it by the second value of the tuple and in case 2 tuples have the same second values, by the first one. I tried this:

sorted(my_list, key=lambda k: (k[1], k[0]), reverse=True)

but what I get is a list sorted only by its second value...for example with this list:

l = [('ee',10), ('oo',11), ('aa', 10)]

I get this output: [('oo', 11), ('ee', 10), ('aa', 10)]

but lexicographically, 'aa' comes before 'ee'...

what am I doing wrong? I tried with my_list.sort() or with a dict but nothing.

the problem is probably the "reverse true" condition, but what I'm trying to get is this output: [('oo', 11), ('aa', 10), ('ee', 10)]

basically I want the reverse true applied only to the first condition of the lambda... it is possible?

2 Answers

You could do something as follows:

output = sorted(l, key=lambda x: (x[1], [-ord(letter) for letter in x[0]]), reverse=True)

output will contain the following:

[('oo', 11), ('aa', 10), ('ee', 10)]

We are keeping the reverse order (descending), but we are passing a list as the second option (which are compared lexicographically by Python too) for sorting which will have the negative ASCII values for each letter. This way, -ord('a') (-97) is greater than -ord('e') (-101)

I guess you should remove the reverse=True option, so that values would be sorted in the "right" order.

>>> l = [('ee',10), ('oo',11), ('aa', 10)]
>>> sorted(l, key=lambda k: (k[1], k[0]), reverse=False)
[('aa', 10), ('ee', 10), ('oo', 11)]
Related