1

I have a table with large number of columns which needs to be populated from a csv file. I have the following __init__ code inside the model definition. [1]

class Table

    column1 = ............
    column2 = .............
    .......

    def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

The code to read from csv file is (load_csv.py)

data_file = "data.csv"
csv_file = csv.DictReader(open(data_file, 'rU'), delimiter=',')
for row in csv_file:
        table_entries = {}
        for key, value in row.items():
                table_entries[key] = value
        table_row = Table(table_entries)
        db.session.add(table_row)
        db.session.commit()

I get the following error on executing load_csv.py

    table_row = Table(table_entries)
TypeError: __init__() takes exactly 1 argument (2 given)

I read that this is because it is using the default __init__ but I am not able to see why it is missing __init__ function I have defined in code. Any help in resolving this problem would be much appreciated.

Community
  • 1
  • 1
Primal Pappachan
  • 25,857
  • 22
  • 67
  • 84

1 Answers1

2

You want to apply the dictionary as keyword arguments:

table_row = Table(**table_entries)

or change your Table() class to receive one argument:

class Table

    def __init__(self, row):
            self.__dict__.update(row)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343