I have a CSV file of sat scores in the format:
State Rate Verbal Math
and the corresponding values for all fifty states. I need a dictionary. The dictionary format for data is the column names as the key and then data under each as lists of the values for that key.I am able to print the list out in the proper format but the lists are not linked to the keys in the dictionary and the dictionary is there, but empty. After many attempts at different methods, this is the best I've come up with:
with open('../sat_scores.csv', mode='r') as f:
sat= {}
label_line =[]
reader = csv.reader(f)
count = 0
for row in reader:
print(row)
if count == 0:
for item in row:
item = sat.keys
count +=1
for row in reader:
for key in sat.keys:
for score in row:
sat[key].append(score)
print(sat)
Any suggestions?
Assuming your rows are unique, this should do it:
with open('../sat_scores.csv', mode='r') as f:
sat = {}
for row in csv.reader(f):
sat[row[0]] = row[1:]
row
is a list. row[0]
has the name of your state. row[1]
, row[2]
and row[3]
have everything else. You can use list slicing and make an entry of State : <List of data>
.
And you're done. It would be good to know that item = sat.keys
does not do what you expect. keys
is a function of the dict, and you are assigning the function to a variable. Look at this:
>>> sat = {}
>>> sat.keys
<built-in method keys of dict object at 0x101b81c08>
What you should be doing is something along these lines:
>>> row = ['OH', '88%', 200, 180]
>>> sat[row[0]] = row[1:]
>>> sat
{'OH': ['88%', 200, 180]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.