希望列标题作为不带任何引号的键,并将列中的后续值作为键的值。
这是我目前所拥有的:
import csv
with open('zinc3.csv') as f:
reader = csv.DictReader(f)
for row in reader:
print row
print ("#1\n")
最佳答案
您可以使用 python 中的 pandas 库,它可以处理:
- 读取 csv 文件:使用 pandas.read_csv
- 将其转换为字典列表:使用 pandas.dataframe.to_dict
这是一个通用的可重现示例(您需要安装 pandas)
from StringIO import StringIO
import pandas as pd
data = """
col1|col2
1|2
21|2
14|2
12|42
10|2
1|27
"""
# StringIO(data) to simulate a csv file
# replace it with the name of your csv file
df = pd.read_csv(StringIO(data), sep="|")
print(df.to_dict(orient="records"))
输出看起来像这样:
[{'col2': 2, 'col1': 1}, {'col2': 2, 'col1': 21}, {'col2': 2, 'col1': 14}, {'col2': 42, 'col1': 12}, {'col2': 2, 'col1': 10}, {'col2': 27, 'col1': 1}]
针对您的具体情况,您需要执行以下操作
import pandas as pd
df = pd.read_csv("zinc3.csv", sep="|")
print(df.to_dict(orient="records"))
关于python - 如何使用键 :value format from a CSV file using Python? 创建字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805821/