Sorting a dictionary field belonging to a list
John Lenton
john at grulic.org.ar
Fri Sep 17 16:51:45 EDT 2004
On Fri, Sep 17, 2004 at 02:51:22PM -0400, Jocknerd wrote:
> I have a list called teamlist which contain dictionaries of teams. These
> are the fields in my team dictionary:
>
> name, won, lost, tied, pf, pa
>
> To print standings I do the following:
>
> def printStandings(teamlist):
> for team in teamlist:
> print (team['name'], team['won'], team['lost'], team['tied'],
> team['pf'], team['pa'])
>
> My question is how would I go about sorting the output based on team['pf']
> for instance?
replace
for team in teamlist:
using the decorate-sort-undecorate pattern,
sortedlist = [(i['pf'], i) for i in teamlist]
sortedlist.sort()
for pf, team in sortedlist:
(this is far faster than calling a python function on each comparison);
in 2.4 you will be able to do
for team in sorted(teamlist, operator.itemgetter('pf')):
--
John Lenton (john at grulic.org.ar) -- Random fortune:
Do not drink coffee in early A.M. It will keep you awake until noon.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20040917/43f80d5c/attachment.sig>
More information about the Python-list
mailing list