Search code examples
pythonpython-3.xcsvpython-dataclasses

"'type' object is not subscriptable" working with dataclasses


Trying to work with entering data from a csv document into a dataclass.

from dataclasses import dataclass
@dataclass

class deck:
    name:str = ''
    length:float = 0.0
    width:float = 0.0
    cost:int = 0

def read(deck):
    with open("Deckingcsv.csv", "r") as d:
        line = d.readline().rstrip('\n') 
        counter = 0
        while line:
            items = line.split(',') 
            print(items)
            deck[counter].name = items[0] 
            deck[counter].length = items[1]
            deck[counter].width = items[2]
            deck[counter].cost = items[3]
            line = d.readline().rstrip('\n') #separates another line
            counter += 1
    return deck


read(deck)
print(deck)

The CSV doc is:

Themon,3.2,2.3,450
Larrec,3.4,3,700
Medrec,2.1,2,500
Parallel,5,4,825
Suncatch,3,3,400
Chantran,9,6,975

However, this is returning this error: TypeError: 'type' object is not subscriptable, line 18 Can't quite figure out where this error is cause from, any help would be appreciated :)


Solution

  • deck is a class. If you are trying to create a deck of items try this:

    from dataclasses import dataclass
    @dataclass
    
    class Item:
        name:str = ''
        length:float = 0.0
        width:float = 0.0
        cost:int = 0
    
    def read(deck):
        with open("Deckingcsv.csv", "r") as d:
            line = d.readline().rstrip('\n') 
            counter = 0
            while line:
                items = line.split(',') 
                print(items)
                item = Item(items[0],items[1],items[2],items[3]
                deck.append(item)
                line = d.readline().rstrip('\n') #separates another line
                counter += 1
        return deck
    
    deck = []
    read(deck)
    print(deck)