使用python中的值对字典列表进行排序的方法

在本文中,您将学习如何使用Python中的值对字典列表进行排序。我们将使用内置的方法调用分类排序的字典。

字典排序步骤

我们将按照下面提到的步骤使用值对字典进行排序。

  • 将包含字典和键的列表传递给已排序的方法。

    • 1.使用lambda函数

    • 2.使用itemgetter方法

    • 我们可以通过两种不同的方式传递键

    让我们看看例子。

    1.使用lambda函数

    示例

    ## list of dictionaries
    dicts = [
       {"name" : "John", "salary" : 10000},
       {"name" : "Emma", "salary" : 30000},
       {"name" : "Harry", "salary" : 15000},
       {"name" : "Aslan", "salary" : 10000}
    ]
    
    ## sorting the above list using 'lambda' function
    ## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
    print(sorted(dicts, key = lambda item: item['salary']))

    如果您运行上述程序,我们将得到以下结果。

    [{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]

    2.使用itemgetter方法

    使用itemgetter对字典进行排序的过程与上述过程相似。我们使用itemgetter方法将值传递给键,这是唯一的区别。让我们来看看。

    示例

    ## importing itemgetter from the operator
    from operator import itemgetter
    ## list of dictionaries
    dicts = [
       {"name" : "John", "salary" : 10000},
       {"name" : "Emma", "salary" : 30000},
       {"name" : "Harry", "salary" : 15000},
       {"name" : "Aslan", "salary" : 10000}
    ]
    
    ## sorting the above list using 'lambda' function
    ## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
    print(sorted(dicts, key = itemgetter('salary')))

    输出结果

    如果您运行上述程序,我们将得到以下结果。

    [{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]