Skip to main content
 首页 » 编程设计

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

2025年02月15日6mfryf

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