Sorting dictionary by 'sub' value

Diez B. Roggisch deetsNOSPAM at web.de
Tue Mar 8 08:39:04 EST 2005


> I have a dictionary of images. I wish to sort the dictionary 'v' by a
> dictionary value using python 2.3. The dictionary value is the date
> attribute as shown here:
> 
>     v[imagename][9]['date']
> 
> This attribute is an extracted EXIF value from the following set:
> 
>     data element [9] of v[imagename]:
> 
>     {'now'        : datetime.date(2005, 3, 7),
>     'y'           : (0x011B) Ratio=72 @ 182,
>     'ctime'       : datetime.date(2005, 3, 7),
>     'width'       : (0xA002) Long=1024 @ 434,
>     'length'      : (0xA003) Long=768 @ 446,
>     'date'        : (0x9004) ASCII=2004:12:07 00:18:20 @ 514,
>     'x'           : (0x011A) Ratio=72 @ 174,
>     'model'       : (0x0110) ASCII=PENTAX Optio 330 @ 156,
>     'size'        : 367415L,
>     'orientation' : (0x0112) Short=1 @ 42}


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


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list