python - 编辑 CSV 文件中的查询

标签 python python-3.x python-2.7 csv dictionary

我的列表中有列名称,我想将值 1 分配给这些列名称,并将值 0 分配给其余列。 例如。

perms_name = ['name','place','thing']

最初 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)

关于python - 编辑 CSV 文件中的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53429052/

相关文章:

python - 运行 python 脚本两次时文件名中出现语法错误?

python - 如何将值列表中的多个项目输入到电子表格中

python - 以毫秒为单位的纪元时间转换为日期时间

python - 获得最小移动以避免方形重叠的算法

python - 如何使用小的单个图像并在整个窗口中重复它以使用 tkinter GUI 使其成为背景图像?

python - 如何获取直接子节点而不是具有相同标签名称的子节点xml minidom python

python selenium 单击链接按钮

javascript - javascript修改后如何获取Html代码?

Python 3.4 输入?

python - python 中的“无”