Sorting a list of dictionaries by dictionary key

Tim Chase python.list at tim.thechases.com
Wed May 3 15:25:35 CEST 2006


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

-tkc






More information about the Python-list mailing list