Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitee13e03

Browse files
committed
Add Chapter 11.7 challenge solution
1 parent7accce6 commitee13e03

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+
importcsv
5+
frompathlibimportPath
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+
withscores_csv_path.open(mode="r",encoding="utf-8")asfile:
18+
reader=csv.DictReader(file)
19+
scores= [rowforrowinreader]
20+
21+
high_scores= {}
22+
foriteminscores:
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+
ifnamenotinhigh_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+
ifscore>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+
withoutput_csv_file.open(mode="w",encoding="utf-8")asfile:
40+
writer=csv.DictWriter(file,fieldnames=["name","high_score"])
41+
fornameinhigh_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)

[8]ページ先頭

©2009-2025 Movatter.jp