Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting associative arrays in Python [duplicate]

Tags:

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?

like image 548
Marty Wallace Avatar asked May 24 '13 21:05

Marty Wallace


1 Answers

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'].

like image 177
unutbu Avatar answered Nov 09 '22 15:11

unutbu