Save the High Scores (Solution)
00:00 This is the final step of this challenge, which is about getting the computed high score dictionary into a CSV file. Let me first remove the pretty-printing code, which I used to verify the correctness of the code written so far.
00:16
Next, I’ll define another Path
object pointing to the output file named high_scores.csv
, which is also going to be located in the same directory, so there’s no need for including any extra path elements.
00:31
Then I’ll open this file for writing. I can essentially copy and paste the with
statement from above, changing the path accordingly, and setting the mode to write. Here I’ll create a csv.DictWriter
object on top of the file,
00:49 and I’ll specify the expected columns, which are the player’s name and their high score.
00:57 Remember that these column names must match the actual keys in the dictionary that we’re about to pass to the writer object. In contrast, my high scores leaderboard only consists of one key, which is the player’s name, so I’ll have to figure out a way of translating between these two representations.
01:16
Once I know the column names, I can tell the writer to place them in the file by calling .writeheader()
. Then I can iterate over the highest scores and write them to the file, but I want to iterate over both the player’s name and their high score at the same time.
01:34
To do that, I’ll call the .items()
method on my dictionary, which returns a sequence of pairs. This allows me to create the desired row as a dictionary comprising the name and high score.
01:50
This is the translation part that I mentioned earlier. Finally, I can use the writer object to append this new dictionary to the output file by calling .writerow()
and passing the row dictionary.
02:04 Fantastic. Let’s save and run the file.
02:08
No errors reported, so I can open the created file named high_scores.csv
, and there you go. That’s the expected output CSV file with unique player names and their corresponding high scores.
02:22 I hope that you arrive at the same result. You can now head over to the final lesson in this course for a quick summary.
Become a Member to join the conversation.