简体   繁体   中英

populating values of a dictionary with lists in python csv package

I have a CSV file of sat scores per state. The file has one state's data(state_name, rate, math, verbal) per one row of the CSV. I have created a dictionary with key values of state, rate, math, verbal with the code below:

with open('../sat_scores.csv', mode='r') as f:
    sat = {}
    reader = csv.reader(f)
    for row in reader:
        for item in row:
            sat[item]=[]
        break

now I to fill the columns with the remaining CSV. The dictionary format for data will be the column names as the key, and the data under each column as the values. I also need to make string numeric columns Rate, Math, and Verbal into floats. I have gotten this far:

    for row in reader:
        for item, key in (row, sat.keys()):
            if key == 'State':
                sat[key].append(item)
                print(sat)
            else:
                new_item = float(item)
                sat[key].append(new_item)
                print(sat)

I cannot figure out how to loop through both the keys of sat dictionary and the items in row simultaneously. Help, please?

You need to keep the order of the header fields:

reader = csv.reader(f)
header = next(reader)
for row in reader:
    for name, value in zip(header, row):
        print(name, value)

You don't really need to do that yourself though, you can use csv.DictReader to get a dictionary per row, with keys taken from the first line:

reader = csv.DictReader(f)
for row in reader:
    print(row)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM