Python 矩阵到字典的转换
我有一个CSV文件,有两列。我想在字典中将第一列存储为键,第二列存储为值,并将其存储为输出文件Python 矩阵到字典的转换,python,csv,numpy,dictionary,matrix,Python,Csv,Numpy,Dictionary,Matrix,我有一个CSV文件,有两列。我想在字典中将第一列存储为键,第二列存储为值,并将其存储为输出文件 import math import numpy import csv from decimal import * #opening Result file with open('output.csv','rb') as file: contents = csv.reader(file) #storing content of Result file in matrix matrix = lis
import math
import numpy
import csv
from decimal import *
#opening Result file with
open('output.csv','rb') as file:
contents = csv.reader(file)
#storing content of Result file in matrix
matrix = list()
for row in contents:
matrix.append(row)
lookup = dict(matrix) # Storing 2 columns of matrix as key:value in dictionary
# open a new csv file for writing.
csv_out = open('MPA.csv', 'wb')
mywriter = csv.writer(csv_out)``
csv_out.close()
我编写的代码无法生成所需的输出。问题是您正在创建一个csv.writer,但没有向文件写入任何内容。这就是文件为空的原因。在关闭文件之前添加以下行:
import csv
import json
with open('test.csv') as f:
with open('MPC.json', 'w') as g:
json.dump(dict([(v[0], v[1]) for v in csv.reader(f)]), g)
csv_out = open('MPA.csv', 'wb')
mywriter.writerows(lookup.items()) # Add this line.
csv_out.close()
如果要用制表符而不是逗号分隔数据,请替换此选项:
mywriter = csv.writer(csv_out)
作者:
您期望什么样的输出以及代码生成什么。它是否会抛出一些错误或生成错误的结果..我希望它使用键n值编写一个输出csv文件。它会生成一个空白的输出文件。但是您的输入已经是一个带有键、值列的csv文件,那么您的输出有什么不同呢?这就是我不知道的。没有任何东西是使用mywriter编写的。这就是为什么什么都没出来。哦,非常感谢你。它写了一个文件。但删除了所有重复的键及其对应的值,如文件,就像早期的RAB10-0.016575 MEF2C-0.019655 SP2 1.24E-01 SP2 0.18870625 SP2 0.0879425 ICK-0.02534625 JAG1-0.01105125,但现在它变成了FOXQ1-0.0905225 CBLB-0.00853 PPP2R2D 0.117835 SP2 0.0879425 SP4-0.02329625 PPP2R2C 0.138485 MUC4 0.0942 MGEA5-0.020625意味着SP2被重复了,现在它被移除了,谢谢你,它帮了很多忙
mywriter = csv.writer(csv_out, delimiter='\t')