Here is a quick and dirty way to sort a list of dictionary based on a key value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | def sort_list_of_dictionary(l, key, deep_copy=True):
''' sorts a list of dictionary based on a key value
by Ritesh Nadhani, riteshn@gmail.com, 08/19/2008
if deep_copy is True then it returns a new list otherwise it does a inline sorting
tests:
l = [
{'key':'R', 'item1':'item1', 'item2':'item2'},
{'key':'Z', 'item1':'item1', 'item2':'item2'},
{'key':'A', 'item1':'item1', 'item2':'item2'},
{'key':'B', 'item1':'item1', 'item2':'item2'},
]
# deep_copy = True
n = sort_list_of_dictionary(l, 'key')
print "Sorted List ", n, " Original List ", l
# deep_copy = False
sort_list_of_dictionary(l, 'key', False)
print "Sorted List ", l
'''
if deep_copy:
result = copy.deepcopy(l)
result.sort(lambda x,y:cmp(x[key],y[key]))
return result
else:
l.sort(lambda x,y:cmp(x[key],y[key]))
|
Or this:
The solution with the "key" argument to the "sort" method or sorted function is definitely more idiomatic and faster but only works with Python >= 2.4.
I wrote a small article in German about the different ways to sort lists, dictionaries and other objects on the German Python wiki:
http://wiki.python.de/Sortierungs-Tutorium