Sorting a Python list by two fields


I have the following list created from a sorted csv

list1 = sorted(csv1, key=operator.itemgetter(1))

I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this?

Answer rating: 390

No need to import anything when using lambda functions.
The following sorts list by the first element, then by the second element. You can also sort by one field ascending and another descending for example:

sorted_list = sorted(list, key=lambda x: (x[0], -x[1]))

Answer rating: 174

like this:

import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))