Reputation: 45
I'm writing a code based on this set of information (http://www.databasebasketball.com/players/playerlist.htm) put into a CSV file.
I want to make a code that determines the BMI of each player, then if their BMI is over 30, it will consider them obese.
However, I have to turn the players' height in feet in height in inches, and I'm not sure how to do this without changing the original CSV file.
So far I have:
import csv
def read_csv(filename):
"""
Reads a Comma Separated Value file,
returns a list of rows; each row is a dictionary of columns.
"""
with open(filename, encoding="utf_8_sig") as file:
reader = csv.DictReader(file)
rows = list(reader)
return rows
# Try out the function
players = read_csv("players.csv")
# Print information on the first player, to demonstrate how
# to get to the data
from pprint import pprint
pprint(players[0])
print(players[0]["lastname"])
print(players[0]["weight"])
total_h_inches = print(players[0]["h_feet"*12])
but it returns an error
Traceback (most recent call last):
File "C:\Python34\hw5.py", line 24, in <module>
h_feet = print(players[0]["h_feet"*12])
KeyError: 'h_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feet'
I know that I am very far from the end result, but I feel like getting through this step will help a lot.
Upvotes: 0
Views: 884
Reputation: 206567
The key misunderstanding, pun intended, is what you expected from
"h_feet"*12
That evaluates to "h_feet" repeated 12 times.
Upvotes: 0
Reputation: 3461
The error is self explanatory: There is no key like 'h_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feet'
in order to convert Feet into inches You should use players[0]['h_feet'] * 12 to convert into inches.
Since 'h_feet' * 12
in the key will change the key name to h_feeth_feet....upto 12 times
.
Also If the Value in the dictionary is string format, You need to typecast it to integer first like int(players[0]['h_feet'])
and then multiply by 12
Upvotes: 0
Reputation: 1483
You'll need to cast the string to an Integer using the built in int() functionality...
total_h_inches = int(players[0]["h_feet"]) * 12
Upvotes: 4