I want to sort the dict开发者_如何学编程 in python. As I am new I don't know where I am going wrong. The below code does sort but the first two entries only.
Pls advice
scorecard ={}
result_f = open("results.txt")
for line in result_f:
(name,score) =line.split()
scorecard[score]=name
for each_score in sorted(scorecard.keys(),reverse =True):
print('Surfer ' + scorecard[each_score]+' scored ' + each_score)
result_f.close()
My guess is you are keeping the scores as strings rather than integers. Strings do not sort the same way as integers. Consider:
>>> sorted(['2','10','15'])
['10', '15', '2']
>>> sorted([2, 10, 15])
[2, 10, 15]
An aside: You map from score to surfer -- the mapping should be reverse of that. Otherwise you would not be able to store two surfers with the same score.
With changes to reverse the mapping and handle the score as an integer:
s = '''Fred 3
John 10
Julie 22
Robert 10
Martha 10
Edwin 9'''
scorecard = {}
for line in s.split('\n'):
name, score = line.split()
scorecard[name] = score
keyfunc = lambda item: (int(item[1]), item[0]) # item[1] is cast to int for sorting
for surfer, score in sorted(scorecard.items(), key=keyfunc, reverse=True):
print '%-8s: %2s' % (surfer, score)
result:
Julie : 22
Robert : 10
Martha : 10
John : 10
Edwin : 9
Fred : 3
If you want the first names in alphabetical order and the scores in descending order change keyfunc
to keyfunc = lambda item: (-int(item[1]), item[0])
and remove reverse=True
from sorted
.
With these changes, the result is:
Julie : 22
John : 10
Martha : 10
Robert : 10
Edwin : 9
Fred : 3
I guess your input file consists lines like
cory 5
john 3
michael 2
heiko 10
frank 7
In that case, you have to convert the score value to an integer to sort properly:
scorecard ={}
result_f = open("results.txt")
for line in result_f:
(name,score) =line.split()
scorecard[int(score)]=name
for each_score in sorted(scorecard.keys(),reverse =True):
print('Surfer ' + scorecard[each_score]+' scored ' + str(each_score))
result_f.close()
If two names might have the same score, perhaps just store scorecard as a list:
scorecard = []
with open("results.txt") as result_f:
for line in result_f:
name,score = line.split()
scorecard.append((score,name))
for score,name in sorted(scorecard,reverse =True):
print('Surfer ' + name +' scored ' + str(score))
精彩评论