[英]Read cvs file to Dictionary python
Please, I need to read CSV file and convert the result to a dictionary. 请,我需要阅读CSV文件并将结果转换为字典。
File input: 文件输入:
The required object after reading like below: 读取后所需的对象如下:
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}})
I write below code but is not working as what I want. 我写下面的代码,但不能按照我想要的工作。 Please help.
请帮忙。
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)
I always use csv.DictReader
and then build the dictionary in the format you want like so: 我总是使用
csv.DictReader
,然后以您想要的格式构建字典,如下所示:
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
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.