[Tutor] dictionaries

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 21 Feb 2002 12:34:36 -0800 (PST)


On Thu, 21 Feb 2002, Christian Ebert wrote:

> > for key in mydict.keys().sort():
> >     # process mydict[key]
> 
> This doesn't work in one line for me. Because sort() sorts
> _in place_?

Yes, the sort() method of lists does it in-place, so the code above
wouldn't work.  However, we can fix that.  Here's a function that'll
return a new sorted list:

###
def fsort(L, f=cmp):
    """A "functional" sort that returns a copy of L, with all its contents
       sorted out."""
    L2 = L[:]
    L2.sort(f)
    return L2
###


And let's make sure that this thing actually works:

###
>>> mydict = {2:'b', 1:'a', 3:'c'}
>>> for key in fsort(mydict.keys()):
...     print mydict[key]
... 
a
b
c
>>> for key in fsort(mydict.keys(),
...                  lambda x,y: -cmp(x, y)):
...     print mydict[key]
... 
c
b
a
###


Good luck!