所以在我打开带有上下文的csv文件之后:
name,email,age
TOM,tom@email.com,13
BOB,bob@email.com,14
ANN,ann@email.com,15
我希望输出如下:
{'name':['TOM','BOB','ANN'], 'email':['tom@email.com','bob@email.com','ann@email.com'], 'age':['13','14','15']}
到目前为止,这是我的代码,如何获得该输出?
def read_table(file_name):
open('file.csv') as lines
dic = {}
i=0
for line in lines:
line = line.split(',')
if line in lines[0]:
key == line[i]
elif line in lines[1:]:
value == line[i]
i+=1
dic[key]=value
print(dic)
有人可以告诉我,我哪里做错了吗?谢谢
答案 0 :(得分:3)
这是另一种方式,如果您想使用Pandas(http://pandas.pydata.org)
import pandas as pd
temp = pd.read_csv("<yourNamedFile.csv")
temp.to_dict("list")
答案 1 :(得分:1)
假设文件不是很大,您可以将整个内容读入内存并使用zip
来切换行和列。
with open("data.csv") as f:
rows = [row.strip().split(",") for row in f]
d = {x[0]:list(x[1:]) for x in zip(*rows)}
# {'age': ['13', '14', '15'],
# 'email': ['tom@email.com', 'bob@email.com', 'ann@email.com'],
# 'name': ['TOM', 'BOB', 'ANN']}
如果您不想使用zip
:
d = {x[0]:x[1:] for x in [[row[i] for row in rows] for i,_ in enumerate(rows[0])]}