Welcome, guest | Sign In | My Account | Store | Cart

Here is a quick and dirty way to sort a list of dictionary based on a key value.

Python, 33 lines
 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]))

2 comments

Kent Johnson 13 years, 3 months ago  # | flag

Or this:

from operator import itemgetter
l.sort(key=itemgetter('key'))
Chris Arndt 13 years, 1 month ago  # | flag

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

Created by riteshn on Wed, 20 Aug 2008 (MIT)
Python recipes (4591)
riteshn's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks