Sorting a dictionary field belonging to a list

J

Jocknerd

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?
 
C

Chris Green

Jocknerd said:
My question is how would I go about sorting the output based on team['pf']
for instance?

The simplest way would be to use the sort method on the list in the
first place. That method takes an optional comparison function that
you would have to write. See help(lst.sort)

lst = [ {'name': 'z'}, {'name': 'd'}, {'name': 'e'} ]

def mycmp(a,b):
return cmp(a['name'],b['name'])

lst.sort(mycmp)

If the original order is important to you, you will be to use
something like copy.copy() to make a copy of the list.
 
J

John Lenton

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 ([email protected]) -- Random fortune:
Do not drink coffee in early A.M. It will keep you awake until noon.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBS05hgPqu395ykGsRApb6AJ44oS3lAA6Q3KjqVMTaKAt4+AHMyACgkG9v
3Unc9K2zG5/vEM/Rs65BnVc=
=p8Kr
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top