

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Data Formats
incomplete
2: Parsing JSON
incomplete
3: Variable-Depth JSON
incomplete
4: Fetching JSON
incomplete
5: CSV Files
incomplete
6: CSV Type Conversion
incomplete
7: Filtering CSV Rows
incomplete
8: Writing CSV Files
incomplete
9: Appending to CSV Files
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
One of the biggest gotchas with csv.DictReader is that every value starts as a string. Even if a column looks numeric, it's still parsed as plain text. Take this CSV snippet:
player,points_per_game,games_played
LeBron James,27.0,71
That row becomes this dictionary:
{"player": "LeBron James", "points_per_game": "27.0", "games_played": "71"}
points_per_game is a stringgames_played is also a string (guh)If you want numbers, convert them explicitly:
games_played = int(row["games_played"])
points_per_game = float(row["points_per_game"])
total_points = points_per_game * games_played
# 1917.0
If you forget to convert types, your code will crash, or it may behave incorrectly, which is arguably even worse! This crashes because Python can't compare a string to an integer:
if row["games_played"] > 50:
print("veteran season")
# TypeError: '>' not supported between instances of 'str' and 'int'
Convert it to an int first:
if int(row["games_played"]) > 50:
print("veteran season")
The worst thing is tweaking a long-running script because you missed a small runtime error. These small, testable changes like string-to-int conversions are everywhere – write tests for them.
Complete the get_average_temperature function. It accepts a list of device reading dictionaries (containing string values) and returns the average temperature.