I need to create a leader board in python 3, the data of the leader board is in an external '.txt' file. Also, the leader board must be sorted from highest to lowest. Also, can you sort it out in a clean leader-board format - without the square brackets, squiggly brackets and the additional commas. I was thinking of maybe using an array or dictionary, but i'm not really sure how to use it
#this is a relevant snippet of my code
f = open("scores.txt", "r")
content = f.read()
content.sort()
print(content)
#this is the text file with the names and scores
Muaadh: 5
Yasir: 6
Zaim: 7
Ishfaq: 5
Tanzeel: 87
Hamzah: 3
Muhammed: 5
Muaadh: 6
Yasir: 5
I have improved @kdq0 code, now it will sort a mixture of double, single and negative digits. I have also shortened the code.This code was written assuming that the text file is named 'Results.txt'
import csv
with open('Results.txt', newline='') as f:
readData = csv.reader(f, delimiter= ':')
sortScores = sorted(readData, key=lambda i: int(i[1]), reverse=True)
for row in sortScores:
print(row[0] +":" +row[1])
Here you go, assuming the data you gave is in a file named sort-test.txt, with no header:
import csv
with open('sort-test.txt', newline='') as f:
data = [{k: v for k, v in row.items()} for row in csv.DictReader(f, delimiter=':', fieldnames=['name', 'score'], quoting=csv.QUOTE_NONE)]
sorted_data = sorted(data, key = lambda i: i['score'], reverse=True)
for x in sorted_data:
print (x['name'] + ': ' + x['score'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With