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
In ascending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))
or in descending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)
like this:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )
Sorting list of dicts using below will sort list in descending order on first column as salary and second column as age
d=[{'salary':123,'age':23},{'salary':123,'age':25}]
d=sorted(d, key=lambda i: (i['salary'], i['age']),reverse=True)
Output: [{'salary': 123, 'age': 25}, {'salary': 123, 'age': 23}]
No need to import anything when using lambda functions.
The following sorts list
by the first element, then by the second element.
sorted(list, key=lambda x: (x[0], -x[1]))
employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])
We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).
employees[0] = Employee's Name
employees[1] = Employee's Salary
This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))