Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python CSV文件编辑中的查询_Python_Python 3.x_Python 2.7_Csv_Dictionary - Fatal编程技术网

Python CSV文件编辑中的查询

Python CSV文件编辑中的查询,python,python-3.x,python-2.7,csv,dictionary,Python,Python 3.x,Python 2.7,Csv,Dictionary,我在列表中有列名,我想给这些列名赋值1,给其余的列赋值0。 前 最初,CSV看起来像: name,age,place,thing,phone_no 我想使csv看起来像: name,age,place,thing,phone_no 1,0,1,1,0 我可以通过这个简单地做到这一点 with open('eggs.csv','a') as csvfile: fieldname = ["name","age","place","thing","phone_no"] writer

我在列表中有列名,我想给这些列名赋值1,给其余的列赋值0。 前

最初,CSV看起来像:

name,age,place,thing,phone_no
我想使csv看起来像:

name,age,place,thing,phone_no
1,0,1,1,0
我可以通过这个简单地做到这一点

with open('eggs.csv','a') as csvfile:
    fieldname = ["name","age","place","thing","phone_no"]
    writer = csv.DictWriter(csvfile,fieldnames=fieldname)
    writer.writeheader()

    writer.writerow(
        {'name': 1,'age':0,'place':1,'thing':1,'phone_no':0}
    )

但是它们的速度更快吗?在本例中,它们只有5列,如果它们有100列,那么我只想为列表中提到的列指定1列。

您可以通过
**
操作符在线解压Python 3中的词典。结合
dict.fromkeys
,无需为每个字段显式写出键和值:

perms_name = ['name','place','thing']
fieldname = ['name', 'age', 'place', 'thing', 'phone_no']

d = {**dict.fromkeys(fieldname, 0), **dict.fromkeys(perms_name, 1)}

{'age': 0, 'name': 1, 'phone_no': 0, 'place': 1, 'thing': 1}
定义一次词典,然后使用:

writer.writerow(d)

或者,对于jpp的答案,您可以使用稍微令人困惑的列表理解来构建字典

perms_name = ['name','place','thing']
fieldname = ['name', 'age', 'place', 'thing', 'phone_no']
d = {field : (1 if field in perms_name else 0) for field in fieldname}
# {'name': 1, 'age': 0, 'place': 1, 'thing': 1, 'phone_no': 0}

如果有任意数量的列可以从csv中读取它们,而不是将它们硬编码到您的脚本中,那么这可能也是值得的。

它成功了,非常感谢。你能帮我做一个新的查询吗?如果在与上面相同的问题中,我想为name字段分配字符串值,其余字段与上面提到的相同,那么我将如何构建我的字典。可能最简单的方法是如上所述构建它,然后在字典理解后重新分配
d['name']='some string value'
(但显然在写之前)。
perms_name = ['name','place','thing']
fieldname = ['name', 'age', 'place', 'thing', 'phone_no']
d = {field : (1 if field in perms_name else 0) for field in fieldname}
# {'name': 1, 'age': 0, 'place': 1, 'thing': 1, 'phone_no': 0}