python - 如何使用键 :value format from a CSV file using Python? 创建字典列表

标签 python csv dictionary

enter image description here

希望列标题作为不带任何引号的键,并将列中的后续值作为键的值。

这是我目前所拥有的:

import csv

with open('zinc3.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print row
        print ("#1\n")

最佳答案

您可以使用 python 中的 pandas 库,它可以处理:

这是一个通用的可重现示例(您需要安装 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/

相关文章:

python - 将大型 CSV 数据集分成更短的 block

python - .get 和字典

python - 如何旋转 matplotlib 条形图?

python - 从其他列表创建列表的更简单方法

read.csv 在 R 中警告 'EOF within quoted string' 但在 EXCEL 中成功读取

java - 如何在某个时刻开始替换字符?

每个键包含两个值的 Python 制表字典

python - 有没有办法用字典中的值替换另一个列表中的列表中的某个值?

python - 如何使用 np.where 更改多个列值?

python - 使用 Numpy 进行大数据集多项式拟合