Re: Sorting dictionary by 'sub' value

From: Rory Campbell-Lange (rory_at_campbell-lange.net)
Date: 03/08/05


Date: Tue, 8 Mar 2005 17:12:56 +0000
To: "Diez B. Roggisch" <deetsNOSPAM@web.de>, Scott David Daniels <Scott.Daniels@Acm.Org>, "Batista, Facundo" <FBatista@uniFON.com.ar>

Thank you all very much for your help.

I did the following and it works:

    imgs=v.keys()
    imgs.sort(lambda a,b: cmp(
              time.strptime(str(v[a][9]['date']), '%Y:%m:%d %H:%M:%S'),
              time.strptime(str(v[b][9]['date']), '%Y:%m:%d %H:%M:%S'))
             )
    for i in imgs:
        ...

Regards,
Rory

On 08/03/05, Diez B. Roggisch (deetsNOSPAM@web.de) wrote:
> l = v.items()
> l.sort(lambda a, b: cmp(a[9]['date'], b[9]['date'])

On 08/03/05, Scott David Daniels (Scott.Daniels@Acm.Org) wrote:
> >You can't sort dicts - they don't impose an order on either key or value.
> >There are ordered dict implementations out there, but AFAIK the only keep
> >the keys sorted, or maybe the (key,values) in the insertion order.
> >
> >But maybe this helps you:
> >
> >l = v.items()
> >l.sort(lambda a, b: cmp(a[9]['date'], b[9]['date'])
>
> In 2.4, this is simple:
>
> ordered_keys = sorted(v, key=lambda name: v[name][9]['date'])
>
> In 2.3, or earlier, use "decorate-sort-undecorate":
>
> decorated = [(value[9]['date'], key)
> for key, value in v.iteritems()]
> decorated.sort()
> result = [key for key, date in decorated]

On 08/03/05, Batista, Facundo (FBatista@uniFON.com.ar) wrote:

> >>> temp_list = [ (x[1][1], x[0]) for x in d.items() ]
...
> >>> temp_list.sort()
> >>> for (tmp, key) in temp_list:

-- 
Rory Campbell-Lange 
<rory@campbell-lange.net>
<www.campbell-lange.net>


Relevant Pages