Python Forum
Outputting Sorted Text files Help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Outputting Sorted Text files Help (/thread-28107.html)



Outputting Sorted Text files Help - charlieroberrts - Jul-05-2020

Hello,
I am currently making a music quiz game and I need to store the top 5 high scores the players of the game achieve.
Currently my code is this...

[python]
d = {} # dictionary to hold the data

with open('Rock60sHIGHSCORE.txt', 'r') as f: # open and
for line in f.readlines(): # read file lines

# assign the name as key to the score's value
d[line.split("'")[0].strip()] = int(line.split(':')[1].strip())

# sort the list and slice the top 5
scoresh = (sorted(d.items(), key=lambda x: x[1])[::-1])[:5]

print(scoresh)
[pyhton]

This is perfectly functional for what I need. However the list it prints out is this..
[('Tom', 51), ('Alex', 9), ('Caitlin', 8), ('Adam', 4), ('Amy', 3)]

Does anyone know how to get rid of the brackets and commas and hopefully put a 'score:' in between them?
I want it to look something like this..
Tom's score: 51
Alex's score: 9
Caitlin's score: 8
Adam's score: 4
Amy's score: 3

Thanks


RE: Outputting Sorted Text files Help - menator01 - Jul-05-2020

Please use proper tags when posting. Make code much easier to read.
mylist = [('Tom', 51), ('Alex', 9), ('Caitlin', 8), ('Adam', 4), ('Amy', 3)]

for data in mylist:
    print(f'{data[0]}: {data[1]}')
Output:
Tom: 51 Alex: 9 Caitlin: 8 Adam: 4 Amy: 3