[Tutor] Sorting dictionary values

Roeland Rengelink r.b.rigilink@chello.nl
Thu, 16 Aug 2001 07:14:39 +0200


Hi Jarrett,

We can't sort dicts , but we can sort lists, so we have to transform the
dictionary.items() into a list that we can sort.

Two alternatives.

1. make a list in such a way that the standard sort function gives us
the desired result

tmplist = [(-data['score'], ID) for (ID, data) in userDB.items()]
tmplist.sort()
for score, ID in tmplist:
    print ID, userDB[ID]

2. use a comp function build to ccmaper a key, value tuple in suck a way
that we get the desired result

def cmp_score((ID1, data1), (ID2, data2)):
    '''compare scores in an ID, data tuple'''
    return -cmp(data1['score'], data2['score'])

tmplist = userDB.items()
tmplist.sort(cmp_score)
for ID, data in tmplist:
    print ID, data

Note the '-' in both the list comprehension an the cmp_function. They
are there to make sure that tmplist sorts in descending order.

By the way, You're probably better of if at some point you try to
approach this in a more OO way. At least a class for the UserData (I
wrote data.score automatically when I first wrote the code above. I was
expecting score to be an attribute of an object). You may also want to
consider some kind of real DB backend.

Hope this helps,

Roeland

"W. Jarrett Campbell" wrote:
> 
[snip]
> >
> >
> > Problem:
> > ------
> > I'm building a "Leader Board" application which tracks user names and displays the top 10 scores from a contest
> W. Jarrett Campbell, Ph.D.
> Member of Technical Staff
> Yield Dynamics, Inc.
> 5838 Balcones Drive, Suite 101
> Austin, TX 78731
> 
> 512.323.9149  phone
> 512.415.1078  mobile
> 512.257.9503  fax>
> > I'm using shelve/pickle for my persistence so basically what I'm confronted with is something that looks like this:
> >
> > userDB = {uniqueUserID:userData}
> >
> > where userData is itself a dictionary like
> >
> > userData = {"fname": "Jarrett",
> >                          "lname": "Campbell",
> >                          "email": "jarrett@ydyn.com",
> >                          "score":"98.8"}
> >
> >
> > What I need to do is find the 10 uniqueUserIDs from userDB where the value of "score" is the in the top 10 of all the records and sort them in order from highest to lowestW. Jarrett Campbell, Ph.D.
> > Member of Technical Staff
> > Yield Dynamics, Inc.
> > 5838 Balcones Drive, Suite 101
> > Austin, TX 78731
> >
> > 512.323.9149  phone
> > 512.415.1078  mobile
> > 512.257.9503  fax.  Once that is done, I have a routine to display the leaderboard.
> >
> >
> > Any suggestions for an efficient way to do this?
> >
> > Jarrett Campbell
> > jarrett@ydyn.com
> >
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"