我有一个csv格式的矩阵,我试图读入并创建一个k:v dict,其中x / y标题是键,值是它们映射到的单元格。 我无法使用任何非标准库或模块。
csv看起来像这样:
,A,B,C
A,1,9,3
B,6,3,5
C,3,8,8
我希望dict看起来像这样:
{AA:1,BA:9,CA:3,AB:6,BB:3,CB:5,AC:3,BC:8,CC:8}
到目前为止:
matrixDict=defaultdict(list)
with open("/path/to/substitutionMatrix.csv", "rb") as confusion_data:
reader = csv.reader(confusion_data, dialect = csv.excel, delimiter = ',')
headers = reader.next()
i,j=1,1
for row in reader:
x=row[0]+headers[i]+(row[j])
for y in row:
matrixDict[x]=y
但是这不起作用,它给了我一个带有列表的键,而不是键应该映射到的单元格值。
答案 0 :(得分:1)
尝试:
import csv
from collections import defaultdict
matrixDict=defaultdict(list)
with open("m.csv", "r") as confusion_data:
reader = csv.reader(confusion_data, dialect = csv.excel, delimiter = ',')
headers = reader.next()
for row in reader:
for i in range(1,len(headers)):
matrixDict[headers[i]+row[0]] = row[i]
print matrixDict
答案 1 :(得分:0)
试试这个:
#!/usr/bin/python
import csv
matrixDict = dict()
with open('csv', 'r') as confusion_data:
reader = csv.reader(confusion_data, dialect=csv.excel, delimiter=',')
headers = reader.next()
for row in reader:
header_index = 1
for col in row[1:]:
key = headers[header_index] + row[0]
matrixDict[key] = col
header_index += 1
print matrixDict
对于给定输入,名为" csv"它输出
{'AA': '1', 'AC': '3', 'AB': '6', 'BA': '9', 'BB': '3', 'BC': '8', 'CC': '8', 'CB': '5', 'CA': '3'}