0

I am given an array with names and grades and i want to sort the grades from highest to lowest and print them in the following format:

Rank Name Grade

I've written some code based on the array given but i'm kind of stuck now. Any help would be awesome. Thanks

grade = {"Nick": 90, "Josh": 80, "Jon" : 70, "David": 100, "Ed": 60, "Kelly": 50}

numerical_grades = grade.values()

ranking = sorted(numerical_grades, reverse = True)
rank=0
print ranking
print "%-8s%-10s%-2s" % ("Rank", "Name", "Grade")

for number_grade in numerical_grades:
     for name in grade:
hon kon
  • 9
  • 4
  • 2
    possible duplicate http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value – Habib Kazemi Jan 14 '16 at 16:03
  • Your code doesn't have any arrays in it. Python by itself doesn't have arrays (only lists). What you have there is a dict (dictionary). – Daenyth Jan 14 '16 at 16:22

3 Answers3

1

You could use the following:

import operator
grade = {"Nick": 90, "Josh": 80, "Jon" : 70, "David": 100, "Ed": 60, "Kelly": 50}
sorted_grades = [(rank, x[0], x[1]) for rank, x in enumerate(sorted(grade.items(), key=operator.itemgetter(1), reverse=True), 1)]
print(sorted_grades))

Output

[(1, 'David', 100), (2, 'Nick', 90), (3, 'Josh', 80), (4, 'Jon', 70), (5, 'Ed', 60), (6, 'Kelly', 50)]

A slightly neater version (with a dictionary output) is as follows:

sorted_grades = dict(enumerate(sorted(grade.items(), key=operator.itemgetter(1), reverse=True), 1))
print(sorted_grades)

Output

{1: ('David', 100), 2: ('Nick', 90), 3: ('Josh', 80), 4: ('Jon', 70), 5: ('Ed', 60), 6: ('Kelly', 50)}
gtlambert
  • 11,711
  • 2
  • 30
  • 48
0

You could sort the entire dictionary and simply iterate over it afterwards:

>>> import operator
>>> grade = {"Nick": 90, "Josh": 80, "Jon" : 70, "David": 100, "Ed": 60, "Kelly": 50}
>>> sorted_by_grade = sorted(grade.items(), key=operator.itemgetter(1))[::-1]
>>> list(enumerate(sorted_by_grade))
[(0, ('David', 100)), (1, ('Nick', 90)), (2, ('Josh', 80)), (3, ('Jon', 70)), (4, ('Ed', 60)), (5, ('Kelly', 50))]
Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26
0
sorted_grades = [(grade[name], name) for name in grades]
sorted_grades.sort(reverse=True)
for n, grade in enumerate(sorted_grades):
    print(n+1, grade[1], grade[0]

This uses a list comprehension to create a list of tuples, (grade, name). You can then use pythons sort function to sort the list highest to lowest. The print statement in the for loop produces the output you appear to desire.

Jeffrey Swan
  • 537
  • 2
  • 8
  • 26