ValueError:dict包含不在字段名称中的字段 [英] ValueError: dict contains fields not in fieldnames

查看:852
本文介绍了ValueError:dict包含不在字段名称中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我这个忙吗?

Can someone help me with this.

我有我的选择查询

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

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

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

但是它给了我这个错误

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

我希望在我下载的csv文件中有以下输出:

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

谢谢.

推荐答案

由于错误指出:来自查询的字典包含的键比您在DictWriter构造函数中指定的字段名称还要多.

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)

但是,蒂姆·皮茨克(Tim Pietzcker)的回答是最好的.

However, Tim Pietzcker's answer is the best.

这篇关于ValueError:dict包含不在字段名称中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆