根据dict的值排序
#方法1
>>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
>>> sorted_x = sorted(x.items(), key=operator.itemgetter(1))
>>> sorted_x
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
#方法2
>>> sorted(x.items(), key=lambda x:x[1])
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
根据dict的key排序
>>> sorted_x = sorted(x.items(), key=operator.itemgetter(0))
>>> sorted_x
[(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
>>>
>>> sorted(x.items(), key=lambda x:x[0])
[(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
>>>
通过列表中的字典的某个值对列表进行排序
>>> aList
[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}, {'age': 23, 'name': 'fuck'}]
>>> sorted(aList, key=operator.itemgetter('age'))
[{'age': 10, 'name': 'Bart'}, {'age': 23, 'name': 'fuck'}, {'age': 39, 'name': 'Homer'}]
>>>
>>> sorted(aList, key=lambda x:x['age'])
[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]