I am having difficulty with presenting the top 5 scores from a csv file. This is my current code:
def leaderboards():
with open('userData.csv', 'r') as data:
reader = csv.reader(data)
for idx, row in enumerate(reader):
print('{} | {} | {}'.format(str(idx), row[0], row[2]))
This is what I currently get:
>>> leaderboards()
0 | Name | Score
1 | Ryan | 3
2 | Liam | 12
3 | Steve | 3
4 | Donald | 3
5 | Alan | 3
6 | Harry | 1
There are two main elements that I would like to implement but don't know how. They are to sort the score so that the highest score is at the top, and to limit the number of players the leaderboards show to 5.
Current code:
with open('userData.csv', 'r') as data:
reader = csv.DictReader(data)
newList = sorted(reader, key=lambda row: row['Score'],
reverse=False)[0:5]
print (' | Name | Score')
for i, r in enumerate(newList):
print('{} | {} | {}'.format(str(i), r['Name'], r['Score']))
Current result:
| Name | Score
0 | Liam | 12
1 | Harry | 2
2 | Ryan | 3
3 | Steve | 3
4 | Donald | 3
It works for the most part, however, the 2 is higher up than the 3. I'm not really sure why but maybe you might realise something. Once again, thank you so much and I'm sorry that I'm just asking so much but this is out of my league in terms of coding knowledge. :D