Skip to content

Commit ee13e03

Browse files
committed
Add Chapter 11.7 challenge solution
1 parent 7accce6 commit ee13e03

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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)

ch11-file-input-and-output/practice_files/scores.csv

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name, score
1+
name,score
22
LLCoolDave,23
33
LLCoolDave,27
44
red,12

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy