Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Find the Highest Scores (Solution)

00:00 At this point, I have the name and score of an individual player, and I want to keep track of their highest score. To do that, I’ll define an empty dictionary called high_scores, which will map unique player names to their highest scores.

00:15 In other words, this dictionary will look similar to the input CSV file, except that each player will only have one entry reflecting their highest score achieved.

00:27 If there are no entries for the current player, whom I can identify by their name,

00:34 then I’ll add a new entry to the high_scores dictionary using whatever the current score is.

00:41 Otherwise, if I already have this player’s score in my leaderboard, then I’ll compare their current score to the old one. Specifically, if the new score is greater than their highest score recorded so far, then I’ll overwrite it with the current score.

01:01 This code looks a bit complicated because of the nested if statements, but I hope that you get a general idea of what it does. In fact, populating a dictionary with data in a loop like this is quite a common scenario in programming.

01:14 Python offers a more elegant and concise way of implementing the same logic, which uses an advanced collection named defaultdict. But since this is a Python Basics course, you don’t need to worry about it just yet.

01:28 You’ll eventually come across it in your Python journey.

01:32 As always, it helps to verify this code. So let me quickly print the high_scores. However, because the output of the regular print() function isn’t always easy to read, I’ll use the pprint() function from the pprint module in Python’s standard library.

01:48 The pprint() function that I want is aliased to pp, and in this case, I won’t bother to put the import statement at the top of the file because this is just a one-off use that I’ll remove afterward.

02:03 Okay, let me save this file and run it. So this is what the high_scores dictionary looks like. The most important observation we can make is that there are no duplicate names.

02:14 Each player has only one score, which we can compare to the original CSV file. For example, the player named LLCoolDave appears three times in the source CSV file, but we only stored his highest score in the resulting dictionary.

02:30 Great. The final step of this challenge is to get that dictionary saved in another CSV file. See you in the next lesson.

Become a Member to join the conversation.