24

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marty Wallace
  • 34,046
  • 53
  • 137
  • 200
  • Did you google "Sorting associative arrays in python"? What was wrong with the documentation you found on sorting associate arrays? – djechlin May 24 '13 at 21:18
  • googling the title of this question...brings you right back to this question. – worc Apr 24 '14 at 16:43

1 Answers1

13

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

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677