[Tutor] Sorting dictionary values

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 15 Aug 2001 11:21:03 -0700 (PDT)


On Wed, 15 Aug 2001, dman wrote:

> On Wed, Aug 15, 2001 at 01:53:31PM -0400, W. Jarrett Campbell wrote:
> | > Problem:
> | > ------
> | > I'm building a "Leader Board" application which tracks user names
> | > and displays the top 10 scores from a contest
> | 
> | > 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 lowest
> | 
> | > Once that is done, I have a routine to display the leaderboard.

[note: This message isn't quite about Python.]


Your program is slowly sounding like a relational database.  *grin* If you
anticipate more complicated queries, you might find it useful to pick up a
relational database and see if it would work well for you.

There are a few free ones out there, such as MySQL:

    http://www.mysql.com/

Postgresql:

    http://postgresql.org/

and Gadfly:

    http://www.chordate.com/kwParsing/index.html



One advantage of using a relational database is that it becomes very easy
to ask different kinds of questions to our data.  For example, your
question:

> | > 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 lowest

could be translated into SQL almost directly:

###
query = """select *
           from users
           order by score
           limit 10"""
###

Take a look at relational databases: you might find them useful.