矩阵转换为字典

时间:2014-11-22 08:04:24

标签: python csv numpy dictionary matrix

我有一个包含2列的CSV文件。我想将第1列作为键存储,将第2列作为值存储在字典中,并将其存储为输出文件。

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()

我编写的这段代码无法生成所需的输出。

2 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

问题是你正在创建一个csv.writer但没有写任何文件。这就是空文件的原因。在关闭文件之前添加以下行:

csv_out = open('MPA.csv', 'wb')
mywriter.writerows(lookup.items())  # Add this line.
csv_out.close()

如果您希望数据以标签分隔,而不是逗号,请将其替换为:

mywriter = csv.writer(csv_out)

由:

mywriter = csv.writer(csv_out, delimiter='\t')