|
| 1 | +# 11.7 Challenge: Create a High Scores List |
| 2 | +# Solution to Challenge |
| 3 | + |
| 4 | +import csv |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +# Change the path below to match the location on your computer |
| 8 | +scores_csv_path = ( |
| 9 | + Path.home() / |
| 10 | + "github/realpython" / |
| 11 | + "python-basics-exercises" / |
| 12 | + "ch11-file-input-and-output" / |
| 13 | + "practice_files" / |
| 14 | + "scores.csv" |
| 15 | +) |
| 16 | + |
| 17 | +with scores_csv_path.open(mode="r", encoding="utf-8") as file: |
| 18 | + reader = csv.DictReader(file) |
| 19 | + scores = [row for row in reader] |
| 20 | + |
| 21 | +high_scores = {} |
| 22 | +for item in scores: |
| 23 | + name = item["name"] |
| 24 | + score = item["score"] |
| 25 | + # If the name has not been added to the high_score dictionary, then |
| 26 | + # create a new key with the name and set its value to the score |
| 27 | + if name not in high_scores: |
| 28 | + high_scores[name] = score |
| 29 | + # Otherwise, check to see if score is greater than the score currently |
| 30 | + # assigned to high_scores[name] and replace it if it is |
| 31 | + else: |
| 32 | + if score > high_scores[name]: |
| 33 | + high_scores[name] = score |
| 34 | + |
| 35 | +# The high_scores dictionary now contains one key for each name that was |
| 36 | +# in the scores.csv file, and each value is that player's highest score. |
| 37 | + |
| 38 | +output_csv_file = Path.home() / "high_scores.csv" |
| 39 | +with output_csv_file.open(mode="w", encoding="utf-8") as file: |
| 40 | + writer = csv.DictWriter(file, fieldnames=["name", "high_score"]) |
| 41 | + for name in high_scores: |
| 42 | + row_dict = {"name": name, "high_score": high_scores[name]} |
| 43 | + writer.writerow(row_dict) |
0 commit comments