Sorting a list of dictionaries by dictionary key
Alex Martelli
aleaxit at yahoo.com
Thu May 4 10:15:14 EDT 2006
Tim Chase <python.list at tim.thechases.com> 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)
>
> Building on Fredrik's solution, for 2.3 (or earlier?), you
> can use
>
> data.sort(lambda a,b: cmp(a['from_datetime'],
> b['from_datetime']))
...and get a potentially very slow sort, if the list is long. Much
faster:
_aux = [ (d['from_datetime'], i, d) for (i, d) in enumerate(data) ]
_aux.sort()
data[:] = [ t[-1] for t in _aux ]
Google Search for DSU or [Decorate Sort Undecorate] ...
Alex
More information about the Python-list
mailing list