0

In Python how can i sort a two item list based on the condition: if first items are not equal do a normal sort (based on the values of first items), and if the first items are equal sort base on the biggness of second items (the bigger value comes first):

Keys of a dictonary like this:

{(0, 3): (3, 8), (0, 11): (4, 4), (1, 4): (5, 32)}

should be then sorted as such:

[(0, 11), (0, 3), (1, 4)]
2

1 Answer 1

3

Use a key function that reverses the sorting of the second elements:

d = {(0, 3): (3, 8), (0, 11): (4, 4), (1, 4): (5, 32)}
print(sorted(d.keys(), key=lambda tup: (tup[0], -tup[1])))  # note the minus
# [(0, 11), (0, 3), (1, 4)]
Sign up to request clarification or add additional context in comments.

2 Comments

or sorted(d, ... looks like a duplicate to me once the dictionary part is removed
here: stackoverflow.com/a/49752932/6451573, that said, the answer solves it, but the question is indeed different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.