Sorting a Python list by two fields

前端 未结 7 1194
不思量自难忘°
不思量自难忘° 2020-11-22 07:51

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

7条回答
  •  甜味超标
    2020-11-22 08:47

    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}]

提交回复
热议问题