[Tutor] Re: [Tutor] Re: Sorting a dictionary in one line?

Magnus Lycka magnus@thinkware.se
Mon Jan 20 18:41:01 2003


Derrick 'dman' Hudson wrote:
> On Sun, Jan 19, 2003 at 11:13:50PM +0100, Magnus Lycka wrote:
> | sortedList = myList; sortedList.sort()
> | 
> | Now there is no ambiguity.

I should obviously have written: "Now this was all pointless."
 
> Just be aware that in the above two lines of code, "both" lists are
> sorted because the two names are really references to the same mutable
> object.  If you want to have a sorted and unsorted version of the
> list, make a copy :
> 
>     sortedList = myList[:]
>     sortedList.sort()

Oops, silly me. I generalized the keys = d.keys() case without
using that thing above my neck. Thanks for correcting that! No
wonder newbies get bitten by mutable objects like that if old
foxes like me fall into the trap. I guess I should follow my
own advice and always type in the interpreter, test properly,
and then paste in my emails. I usually do that, but now and then
I get afflicted by hubris and think that I can use my brain as a
python interpreter for simple one or two line scripts...

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se