Sorting a list of dictionaries by dictionary key
Eric Deveaud
edeveaud at pasteur.fr
Wed May 3 09:13:17 EDT 2006
Nico Grubert wrote:
> Hi there,
>
> 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?
sort can take a comparaison function. which specification are
takes 2 elements
returns a negative value if elem1 is lesser than elem2
returns a positive value if elem1 is grater than elem2
returns zero if elem1 == elem2
you may write such fuction
def dictionary_datetime_sorter(d1, d2):
date1 = d1['from_datetime']
date2 = d2['from_datetime']
if date1 < date2: return -1
elif date1 > date2: return 1
else: return 0
you'll have to find out how to compare 2 DateTime
and then, in order to sort your list
your_dictionary_list.sort(dictionary_datetime_sorter)
Eric
--
« Voyons-voir : est-ce que ma question est vraiment conne ? Oh oui,
vraiment trop conne, je vais poster dans "premiers-pas", je posterai
dans "configuration" quand je serai moins con. »
-+-JLC - Guide du Neuneu d'Usenet - Bien configurer sa question -+-
More information about the Python-list
mailing list