Sorting associative arrays in Python
This question already has an answer here:
Use the sorted
function's key
parameter:
sorted(people, key=lambda dct: dct['name'])
There is an excellent Sorting HOWTO which explains how this works.
>>> 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'}]
Alternatively, you could use
import operator
sorted(people, key=operator.itemgetter('name'))
Using operator.itemgetter('name')
is slightly faster than using lambda dct: dct['name']
.
上一篇: 我如何根据字典中的值对字典列表进行排序?
下一篇: 在Python中排序关联数组