Sorting a list of dictionaries by dictionary key

Fredrik Lundh fredrik at pythonware.com
Wed May 3 10:34:44 EDT 2006


Nico Grubert wrote:

> > assuming that DateTime returns something that compares correctly, you can
> > do something like:
> >
> >     def sortkey(item):
> >         return item.get("from_datetime")
> >
> >     data.sort(key=sortkey)
> >
> > (assuming Python 2.4 or later)
>
> Thank you very much, Frederik. Unfortunately, I can only use
> Python 2.3.5.

under Python 2.3, you can either use a custom compare function (which
may be slow if you have lots of items, because a sort has to do more com-
pares than there are items):

    def compare(a, b):
        return cmp(sortkey(a), sortkey(b))

    data.sort(compare)

or do your own "decorate-sort-undecorate" (which is what the "key"
option is doing for you):

    data = [ (sortkey(x), x) for x in data ] # decorate
    data.sort()
    data = [ x[1] for x in data ] # undecorate

</F>






More information about the Python-list mailing list