ValueError: dict contains fields not in fieldnames

后端 未结 3 721
醉话见心
醉话见心 2020-12-03 04:57

Can someone help me with this.

I have my Select query

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

And I want the content o

相关标签:
3条回答
  • 2020-12-03 04:59

    As the error message clearly states, your dictionary contains keys that don't have a corresponding entry in your fieldnames parameter. Assuming that these are just extra fields, you can ignore them by using the extrasaction parameter during construction of your DictWriter object:

    writer = csv.DictWriter(csvfile, fieldnames=["Bio_Id","Last_Name","First_Name","late","undertime","total_minutes", "total_ot", "total_nsd", "total_absences"], 
                            extrasaction='ignore', delimiter = ';')
    
    0 讨论(0)
  • 2020-12-03 05:04

    Hi all thank you for answering. I finally found out how to make it. here is the code

        w = csv.writer(file(r'test.csv','wb'), delimiter=';')
        w.writerows([["Bio Id","Last Name",.....]])
        w.writerows(db.session.execute(selectAttendance))
        db.session.commit()
    
    0 讨论(0)
  • 2020-12-03 05:16

    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.

    0 讨论(0)
提交回复
热议问题