[Tutor] help with sorted()

Emile van Sebille emile at fenx.com
Tue Aug 19 21:50:02 CEST 2008


Rick Pasotto wrote:
> I have a dictionary that looks like: d = {k:[v1,[v2,v3,v4]]}
> 
> v1,v2,v3,v4 are integers.
> 
> I want to print the dictionary sorted by v1, high to low.
> 
> sorted(d,operator.itemgetter(0),reverse=True)

You need to pass a compare function in... try

for ii in sorted(d,lambda ii,jj: cmp(d[jj][0],d[ii][0])): d[ii]

HTH,

Emile


> 
> gives me the keys in some order different than if I just looped through
> the dictionary and not in key order but also not in any order that I can
> see. It really appears random.
> 
> sorted(d) does give me a sorted list of keys.
> 
> How do I sort on v1? How would I sort on v3?
> 



More information about the Tutor mailing list