We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

CSV Type Conversion

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 string
  • games_played is also a string (guh)

Convert Values

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

Wrong Types Break Code

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.

Assignment

Complete the get_average_temperature function. It accepts a list of device reading dictionaries (containing string values) and returns the average temperature.