Sorting a list of dictionaries by dictionary key

Fredrik Lundh fredrik at pythonware.com
Wed May 3 09:07:41 EDT 2006


Nico Grubert wrote:

> I am looking for a way to sort a list containing dictionaries.
>
> This is my example list:
> [{'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00
> GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18
> 12:45:00 GMT+2')}, {'Title': 'GHI', 'from_datetime':
> DateTime('2006/03/10 12:45:00 GMT+2')}]
>
> I want to sort the list by dictionary's key 'from_datetime' so the
> sorted list should be:
>
> [{'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00
> GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18
> 12:45:00 GMT+2')}, {'Title': 'ABC', 'from_datetime':
> DateTime('2006/04/25 12:45:00 GMT+2')}]
>
> Any idea how I can sort this list?

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)

</F> 






More information about the Python-list mailing list