Find the Highest Scores (Solution)
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: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.
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.
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.
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.
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.
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.
Become a Member to join the conversation.