How can an associative array be sorted by key in Python?
I have the following structure:
people = [
{'name' : 'Bob', 'number' : '123'},
{'name' : 'Bill', 'number' : '234'},
{'name' : 'Dave', 'number' : '567'},
]
I want to sort by name. Is there a built in function to do this?
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']
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With