[Tutor] sorting a list of dictionaries

Kent Johnson kent37 at tds.net
Thu Dec 9 19:40:14 CET 2004

If you can use Python 2.4 it is very simple using the new key= parameter to sort and 

 >>> import operator
 >>> ds = [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':36}]
 >>> ds.sort(key=operator.itemgetter('name'))
 >>> ds
[{'name': 'bar.txt', 'size': 36}, {'name': 'foo.txt', 'size': 35}]
 >>> ds.sort(key=operator.itemgetter('size'))
 >>> ds
[{'name': 'foo.txt', 'size': 35}, {'name': 'bar.txt', 'size': 36}]

Otherwise you should use decorate - sort - undecorate. The idea here is to make a new list whose 
values are pairs of (key, item) for each data item in the original list. The new list is sorted, 
then a final list is extracted containing only the items in the desired order:

 >>> d2 = [ (d['name'], d) for d in ds ]
 >>> d2.sort()
 >>> ds = [ d for (name, d) in d2 ]
 >>> ds
[{'name': 'bar.txt', 'size': 36}, {'name': 'foo.txt', 'size': 35}]


Larry Holish wrote:
> Hello,
> I have a list of dictionaries, each representing info about a file,
> something like:
> [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
> I want to present a sorted list of all the files' data, sorting on the
> keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping)
> across all the dictionaries. Can someone point me towards an efficient
> solution for accomplishing the sort? (The list has 1000s of files).
> Thanks in advance,

More information about the Tutor mailing list