Python-如何对字典集合进行排序

一: 通过lambda表达式来指定排序字段

salaries = [{'Alice': 100000, 'Bob': 24000},
            {'Alice': 121000, 'Bob': 48000},
            {'Alice': 12000, 'Bob': 66000}]

Use the sorted() function with key argument to create a new dic.
sorted_salaries = sorted(salaries, key=lambda d: d['Alice'])

print(sorted_salaries)

二:使用集合遍历器(Itemgetter)来指定排序字段

from operator import itemgetter

salaries = [{'Alice': 100000, 'Bob': 24000},
            {'Alice': 121000, 'Bob': 48000},
            {'Alice': 12000, 'Bob': 66000}]

sorted_salaries = sorted(salaries, key=itemgetter('Alice'))
print(sorted_salaries)

三:指定多个排序字段

db = [{'username': 'Alice', 'joined': 2020, 'age': 23},
      {'username': 'Bob', 'joined': 2018, 'age': 19},
      {'username': 'Alice', 'joined': 2020, 'age': 31}]
db_sorted = sorted(db, key=lambda row: (row['username'],
                                        row['joined'],
                                        row['age']))

print(db_sorted)

四:指定升序or降序

db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23},
      {'username': 'Bob', 'joined': '2020-08-08', 'age': 19},
      {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}]

db_sorted = sorted(db, key=lambda row: row['joined'], reverse=True)
print(db_sorted)

或者
db_sorted = sorted(db, key=lambda row: row['joined'])[::-1]

posted @ 2021-01-08 11:00  小泥巴2008  阅读(1539)  评论(0编辑  收藏  举报