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?

The common idiom for this is called decorate-sort-undecorate.

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

decorated_list = [(d['from_datetime'], d) for d in unsorted_list]
decorated_list.sort()
sorted_list = [t[1] for t in decorated_list]

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to