在Python中排序关联数组

这个问题在这里已经有了答案:

  • 如何根据Python中字典的值对字典列表进行排序? 17个答案

  • 使用sorted函数的key参数:

    sorted(people, key=lambda dct: dct['name'])
    

    有一个很好的排序HOWTO解释了这是如何工作的。


    >>> people = [
        {'name' : 'Bob', 'number' : '123'},
        {'name' : 'Bill', 'number' : '234'},
        {'name' : 'Dave', 'number' : '567'},
    ]       
    >>> sorted(people, key=lambda dct: dct['name'])
    [{'name': 'Bill', 'number': '234'}, 
     {'name': 'Bob', 'number': '123'}, 
     {'name': 'Dave', 'number': '567'}]
    

    或者,你可以使用

    import operator
    sorted(people, key=operator.itemgetter('name'))
    

    使用operator.itemgetter('name')比使用lambda dct: dct['name']稍快。

    链接地址: http://www.djcxy.com/p/70761.html

    上一篇: Sorting associative arrays in Python

    下一篇: How to sort a Python dictionary by value?