Search code examples
pythonlistfilesortingexternal

Im not sure how i can make my program sort and read from an external file


I am creating a dice game in a nut shell and the scores get saved to an external file name 'scores'

Krystian: 5
Adam: 7
Unknown: 2
AWD: 18
Muaadh: 5
Yasir: 6
Zaim: 7
Ishfaq: 5
Tanzeel: 87
Hamzah: 3
Mohammed: 5
Robert: 6
Yasir: 5
Krystian: 61
Natalie: 72

and these are the usernames and their scores. I have seen some csv sort algorithms but the problem is that i am only a beginner and i don't have a clue on how they work so i can't really use them. What im really looking for is an explanation of how to sort them from highest score down to the lowest score and i want the program to print out the top 5 players.

with open('scores.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'])

so far that is all i have managed to 'copy' from other posts but it still doesn't work properly. I think it's worth sharing that when u run the program it asks the user for their name, then it gets their score then it saves to the file and at the very end is where i ask the user if they would like to see top 5 players , so that is where i want my program to sort the external file and print out the top 5 players. I do apologise as i have seen many posts like this but the only reason i post this myself is because i really don't understand any of them. Thanks for making it this far.


Solution

  • You have got it 80% of the way, you just need to isolate the top 5 scores, get rid of the leading white spaces, and convert the strings to integers. I would recommend using a dictionary instead of a csv file, but what you have is working. You also have duplicates in your csv, which using a dictionary would fix.

    with open('scores.txt', newline='') as f:
                # Stripping the leading spaces off of the numbers and names
       data = [{k.strip(): v.strip() for k, v in row.items()} for row in csv.DictReader(f, delimiter=':', fieldnames=['name', 'score'], quoting=csv.QUOTE_NONE)]
    
                                                  # Making the string an integer
       sorted_data = sorted(data, key = lambda i: int(i['score']), reverse=True)
                           # Isolating the top 5 results using indexes.
       for x in sorted_data[:5]:
           print (x['name'] + ': ' + x['score'])