Python ValueError: dict 包含不在字段名中的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26944274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:12:50  来源:igfitidea点击:

ValueError: dict contains fields not in fieldnames

pythoncsv

提问by akbsmile

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:

我想要我的选择查询的内容并在下载 csv 文件时包含一个标题,所以我做了这个查询:

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:

我想在我下载的 csv 文件中有这样的输出:

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.

先感谢您。

采纳答案by bgusach

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

正如错误所述:来自查询的字典包含的键比您在 DictWriter 构造函数中指定的字段名称多。

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.

然而,Tim Pietzcker 的回答是最好的。

回答by Tim Pietzcker

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

正如错误消息明确指出的那样,您的字典包含在您的fieldnames参数中没有相应条目的键。假设这些只是额外的字段,您可以通过extrasaction在构造DictWriter对象期间使用参数来忽略它们:

writer = csv.DictWriter(csvfile, fieldnames=["Bio_Id","Last_Name","First_Name","late","undertime","total_minutes", "total_ot", "total_nsd", "total_absences"], 
                        extrasaction='ignore', delimiter = ';')

回答by akbsmile

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()