[Tutor] Sort pointers -
Kent Johnson
kent37 at tds.net
Fri Nov 26 14:45:36 CET 2004
Kent Johnson wrote:
> 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
The Python 2.4 sorted() function also takes an optional key parameter,
so you can print a dictionary sorted by value very simply:
>>> miscPeople= {'James Bond' : '007' , 'Enid Blyton' : '005' , 'Enid
Blyton also' : '006' , 'Captain Planet' : '000' }
>>> import operator
>>> for name, code in sorted(miscPeople.items(),
key=operator.itemgetter(1)):
... print name, code
...
Captain Planet 000
Enid Blyton 005
Enid Blyton also 006
James Bond 007
operator.itemgetter(1) produces a *function* which, when given a
sequence, returns item 1 of the sequence:
>>> get1 = operator.itemgetter(1)
>>> get1( ['a', 'b'] )
'b'
>>> get1(miscPeople.keys())
'Captain Planet'
Kent
More information about the Tutor
mailing list