![]() |
Conditional sorting in Python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Conditional sorting in Python (/thread-11368.html) |
Conditional sorting in Python - amirt - Jul-05-2018 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)] RE: Conditional sorting in Python - buran - Jul-05-2018 data = {(0, 3): (3, 8), (0, 11): (4, 4), (1, 4): (5, 32)} print(sorted(sorted(data.keys(), key=lambda x: x[1], reverse=True), key=lambda x:x[0])) [(0, 11), (0, 3), (1, 4)] https://wiki.python.org/moin/HowTo/Sorting#Sort_Stability_and_Complex_Sorts |