Search code examples
pythoncsv

ValueError: dict contains fields not in fieldnames


Can someone help me with this.

I have my Select query

selectAttendance = """SELECT * FROM table """

And I want the content of my select query and include a header when I download the csv file, So I did this query:

with open(os.path.join(current_app.config['UPLOAD_FOLDER'], 'csv.csv'), 'wb') as csvfile:
                writer = csv.DictWriter(csvfile,fieldnames  = ["Bio_Id","Last_Name","First_Name","late","undertime","total_minutes", "total_ot", "total_nsd", "total_absences"], delimiter = ';')
                writer.writeheader()
                writer.writerow(db.session.execute(selectAttendance))
            db.session.commit()

but it gives me this error

**ValueError: dict contains fields not in fieldnames**

I want to have like this output in my downloaded csv file:

Bio_Id Last_Name First_Name late undertime total_minutes total_ot total_nsd total_absences
1      Joe       Spark       1     1            2            1        1          1

Thank you in advance.


Solution

  • As the error states: the dictionary that comes from the query contains more key than the field names you specified in the DictWriter constructor.

    One solution would be to filter that in advance, something like this:

    field_names = ["Bio_Id","Last_Name", ...]
    writer = csv.DictWriter(csvfile,fieldnames=field_names , delimiter = ';')
    writer.writeheader()
    data = {key: value for key, value in db.session.execute(selectAttendance).items()
            if key in field_names}
    writer.writerow(data)
    

    Another solution could be to construct the query using only those fields:

    query = 'SELECT %s FROM table' % ', '.join(field_names)
    

    However, Tim Pietzcker's answer is the best.