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?

2
  • Did you google "Sorting associative arrays in python"? What was wrong with the documentation you found on sorting associate arrays? Commented May 24, 2013 at 21:18
  • googling the title of this question...brings you right back to this question. Commented Apr 24, 2014 at 16:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.