1

So I have a 2D array of data taken from an excel spreadsheet which I'm currently sorting based on a column with data on criticality.

#rows contains my data that I'm sorting, it's a 2D array
searchdict = dict(Critical=1, High=2, Medium=3, Low=4)
rows.sort(key=lambda row: searchdict.get(row[11], 5))

I'd like to sort based on another column if it's a tie for that column, anyone know how to approach this? Thanks in advance for any help.

FYI: the other column contains numerical data

1

3 Answers 3

9

Use a tuple in your key. This is method is generally considered more "pythonic" than doing two sorts in a row.

key=lambda row: (searchdict.get(row[11], 5), row[other_column]))
Sign up to request clarification or add additional context in comments.

2 Comments

The OP said that the other column is numerical so there is no need for an other call to searchdict.get. (BTW: thg's answer was incorrect also because if you want to do 2 sorts you must first sort by the secondary key, and the by the primary key.)
Oops, you're right. And thg's answer was also incorrect because sort() normally returns None instead of the sorted list (sorted() is normally used for that).
1

The best option would be to use key with python's tuple ordering.

#rows contains my data that I'm sorting, it's a 2D array
searchdict = dict(Critical=1, High=2, Medium=3, Low=4)
rows.sort(key=lambda row: (searchdict.get(row[11], 5), searchdict.get(row[<secondary column index here>], 5)))

This plays off of the fact that the leftmost element in a tuple is considered to be more significant during comparisons, demonstrated here:

>>> (6, 5) > (5, 6)
True
>>> (6, 5) > (6, 4)
True
>>> (6, 5) > (6, 6)
False
>>> (2, 1, 1) > (1, 1000, 1000)
True 

Comments

0

Use a tuple as return from your sort key function:

rows.sort(key=lambda row: (searchdict.get(row[11], 5), row[17]))

Python sorts for item with index 0 first than for item with index 1.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.