associative array

Peter Otten __peter__ at web.de
Thu Apr 1 07:20:57 EDT 2010


Javier Montoya wrote:

> Is it possible to sort the dictionary by the student's grades in
> descending order?

You cannot sort dictionaries, but you can put dictionary items into a list 
and then sort that.

Assumming that you have a dictionary student_dict that maps student IDs to 
Student instances and a function get_grade() to find a student's grade you'd 
do

def get_grade(student):
    return course[student.student_id].grade # or whatever it takes

students_by_grade = sorted(student_dict.itervalues(), key=get_grade, 
reverse=True)

for student in students_by_grade:
    print student.first_name, student.last_name

However, problems like the above are normally handled best using a SQL 
database, so I recommend that you have a look at

http://docs.python.org/library/sqlite3.html

Peter



More information about the Python-list mailing list