hon kon
hon kon

Reputation: 9

Python sorting arrays

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:

Upvotes: 0

Views: 138

Answers (3)

gtlambert
gtlambert

Reputation: 11961

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)}

Upvotes: 1

Jeffrey Swan
Jeffrey Swan

Reputation: 537

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.

Upvotes: 0

Alexander Ejbekov
Alexander Ejbekov

Reputation: 5940

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))]

Upvotes: 0

Related Questions