@Ald, your code looks good to me:
scores = {}
result_f = open("results.txt")
for line in result_f:
(name, score) = line.split()
scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
print('surfer ' + scores[each_score] + ' scored ' + each_score)
# or an alternate formulation:
def get_scores_dict(file_name):
with open(file_name) as in_file:
return {k:v for k,v in [line.split() for line in in_file]}
scores_dict = get_scores_dict('results.txt')
print('The top {} scores were:'.format(len(scores_dict)))
for player in sorted(scores_dict):
print('surfer {} scored {}'.format(player, scores_dict[player]))
Seem to work as expected if results.txt contains:
Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31
A few notes on the alternate version:
- It creates a separate function to build a dict from a file to increase the likelihood of reuse elsewhere.
- It uses the
with open() syntax which is generally preferred because it automatically calls .close() for you.
- It uses both a list comprehension and a dict comprehension which are quite optimized but can be confusing.
- It uses
sorted() to put the players into alphabetical order (although score order might be even more useful).
- It drops the use of
.keys() which is optional when iterating thru all of the items in a dict.
- It uses
str.format() which is the generally preferred way to build up strings because it is more efficient than concatenation (+).
NOTE: In the upper right of each of your posts to this forum is the word edit which you can tap to modify your post.