使用python从csv文件字典



有一个有 3 列的 csv 文件,我试图制作字典。首先我阅读了文件:

fin = open('example.csv', 'r')

有了这些列,我怎么能制作字典?

编辑以回应 OP 评论

我想你要求的就是转身

a,123,456
b,333,444
c,888,3434

{'a': ('123', '456'), 'b': ('333', '444'), 'c': ('888', '3434')}

如果是这样,一种解决方案是使用 csv.reader 解析文件、迭代行并填充最终字典。

with open('example.txt', 'rb') as src_file:
    csv_file = csv.reader(src_file)
    data = {}
    for row in csv_file:
        data[row[0]] = (row[1], row[2])
    print(data)

请参阅 http://docs.python.org/2/library/csv.html 中的csv模块文档

您可以在csv模块中使用dict_writer。

import csv
fieldnames = ['Column1', 'Column2', 'Column3']
dict_writer = csv.DictWriter(file('your.csv', 'wb'), fieldnames=fieldnames)
dict_writer.writerow(fieldnames)
dict_writer.writerows(rows)

你没有说值应该是什么样子,所以:

d={}
with open('example.csv', 'r') as file:
    for line in file:
        lst = line.strip().split(',')
        d[lst[0]] = lst[1:]

这将输出如下内容:

{'key1': ['v1', 'v2'], 'key2': ['v1', 'v2']}

你也可以使用 numpy loadtxt 并创建字典。

  from numpy import loadtxt
  a,b,c = loadtxt('filename.csv', sep=',', unpack=true)
  dictionary = dict(zip(a,(b,c)))

最新更新