[Tutor] Sort pointers -

Kent Johnson kent37 at tds.net
Thu Nov 25 14:15:40 CET 2004


No, this will not print miscPeople sorted by key except perhaps by accident.

Jacob S. wrote:
> If your curious and you want the output described, this would work.
> 
> ----------------------------------------------------------------------------
> --
> miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid Blyton
> also' : '006' , 'Captain Planet' : '000' }
> miscPeople.keys().sort()

miscPeople.keys() makes a new list. It is not a reference to the live 
dict keys - IOW changes to the list are *not* reflected in the dict. You 
sort the list but you don't keep a reference to it.

> for x in miscPeople.keys():
>     print x,miscPeople[x]

Now you get a fresh copy of the keys and iterate over it. This copy is 
in no particular order.

You have to get the keys, sort them, and iterate the sorted copy:
keys = miscPeople.keys()
keys.sort()
for x in keys:
   print x, miscPeople[x]

In Python 2.4 (there it is again), there is a built-in sorted() function 
that *returns* a sorted copy of any iterable. So you can do this:
for x in sorted(miscPeople.keys()):
   print x, miscPeople[x]

I would actually do it this way:
for name, code in sorted(miscPeople.items()):
   print name, code

(Liam, are you ready to upgrade yet? :-)

Kent



More information about the Tutor mailing list