associative array

Peter Otten __peter__ at
Thu Apr 1 13:20:57 CEST 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 

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

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

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


More information about the Python-list mailing list