Sorting dictionary by 'sub' value
Scott David Daniels
Scott.Daniels at Acm.Org
Tue Mar 8 09:28:12 EST 2005
Diez B. Roggisch wrote:
>>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']
>>...
>
> 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]
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list