>>> 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}]
Kent
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,
_______________________________________________ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor