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.
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.
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: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.
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.
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.
Become a Member to join the conversation.