23

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,030
  • 21
  • 100
  • 124
Marty Wallace
  • 31,458
  • 53
  • 132
  • 196
  • 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

12

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
  • 777,569
  • 165
  • 1,697
  • 1,613