Python - CSV rows into multiple lists

Viewed 478

I want to convert each of the rows in my csv file into lists. But the below code doesn't work , it rather converts all the columns into lists

def data():
import csv

f=open("mydata.csv","r")
reader=csv.reader(f)

Type=[]
BusPsngr=[]
Bus=[]
PersoVeh=[]
LoadTrks=[]



for row in reader:
    Type.append(row[0])
    BusPsngr.append(int(row[1]))
    Bus.append(int(row[2]))
    PersoVeh.append(int(row[3]))
    LoadTrks.append(int(row[4]))

my data

so my first lists should be List1=['Type','2000',........,'2012'] and so on for each row.

1 Answers

If all you need is lists from the rows as they are in the file,

with open("mydata.csv") as f:
  lines = list(csv.reader(f))

will make lines something like

[
  ["Type", "2000", ...],
  ["Bus Pass", "...."],
]

You could then unpack this into 5 separate lists:

Type, BusPsngr, Bus, PersoVeh, LoadTrks = lines[:5]

EDIT

If you want to skip the first column, you can use a list comprehension to clip it out while reading the CSV:

with open("mydata.csv") as f:
  lines = [line[1:] for line in csv.reader(f)]

EDIT 2

To read the data into a dict (just in case the lines are in a different order than you expect) and to convert the values into integers at the same time...

with open("mydata.csv") as f:
  data = {
    line[0]: [int(v) for v in line[1:]]
    for line
    in csv.reader(f)
  }
print(set(data.keys()))
Type = data["Type"]
BusPsngr = data["Bus Passenger"]  # or whatever...
Related