将cvs文件读入Dictionary python

时间:2016-10-14 07:40:58

标签: python csv dictionary

请,我需要阅读CSV文件并将结果转换为字典。

文件输入:

enter image description here

如下所示的所需对象:

defaultdict(<type 'dict'>, {‘Book’: {‘Book’: 1.0, ‘Afnan’: 0, ‘Location’: 0, ‘Love’: 0}, ‘Afnan’: {‘Book’: 0, ‘Afnan’: 1.0, ‘Location’: 0.71, ‘Love’: 0}, ‘Location’: {‘Book’: 0, 'Afnan’: 0.71, ‘Location’: 1.0, ‘Love’: 0}, ‘Love’: {‘Book’: 0, ‘Afnan’: 0, ‘Location’: 0, ‘Love’: 1.0}})

我写下面的代码但是没有按照我想要的方式工作。请帮忙。

reader = unicode_csv_reader(open('cos3.csv'))
x=list(reader)
for i in x:
    if isinstance(i,float):
        arr=np.array(x).astype('float')
    else:
        arr=np.array(x).astype('string')
d=defaultdict(dict)
for a in arr:
    for b in arr:
        d[a][b]=arr(a)

1 个答案:

答案 0 :(得分:0)

我总是使用csv.DictReader然后以您想要的格式构建字典:

enter image description here

import csv
import os
cwd = os.getcwd()


d_out = {}
with open(cwd+'\\example.csv', 'rb') as file_in:
    reader = csv.DictReader(file_in, restkey=None, restval=None, dialect='excel')
    for row in reader:
        d_out.setdefault(row['Key'], {'Book':row['Book'], 'Afnan':row['Afnan'], 'Location':row['Location'], 'Love':row['Love']})


print d_out

希望这有帮助!