Home > Back-end >  How to convert a line in csv to a list of objects
How to convert a line in csv to a list of objects

Time:11-16

Each line in my csv file is data on a pet. Ex"Fish, Nemo, April 2nd, Goldfish, Orange." I would like to import that file and create a new object for that pet depending on its type(the first string in each line). For example data about the fish would be stored in a fish object. I then want to put each object into a list.

I've tried:

pets = []
    with open('desktop/cs110/pets.csv', 'r') as file:
        csvReader = csv.reader(file, delimiter=',')
        for row_pets in csvReader:
            pets.append(row_pets)
    columnNames = ['firstCol', 'secondCol', 'thirdColomn']
    lstPets = []
    for row_pets in pets:
        lstPets.append({key: value for key, value in zip(columnNames, row_pets)})
return lstPets

CodePudding user response:

With csv.DictReader you can accomplish what your current code attempts by specifying fieldnames and assuming your "object" desired is a dictionary:

pets.csv

Fish,Nemo,April 2nd,Goldfish,Orange
Cat,Garfield,June 1st,Tabby,Orange

test.py

import csv
from pprint import pprint

with open('pets.csv', newline='') as file:
    reader = csv.DictReader(file, fieldnames='type name bday species color'.split())
    data = list(reader)

pprint(data)

Output

[{'bday': 'April 2nd',
  'color': 'Orange',
  'name': 'Nemo',
  'species': 'Goldfish',
  'type': 'Fish'},
 {'bday': 'June 1st',
  'color': 'Orange',
  'name': 'Garfield',
  'species': 'Tabby',
  'type': 'Cat'}]
  • Related