ActiveState Code

Recipe 576433: Sorting a list of dictionary based on a key value


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

Python
 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]))

Comments

  1. 1. At 12:25 p.m. on 20 aug 2008, Kent Johnson said:

    Or this:

    from operator import itemgetter
    l.sort(key=itemgetter('key'))
    
  2. 2. At 3 a.m. on 19 oct 2008, Chris Arndt said:

    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

Sign in to comment