如何在python中将csv读入字典?

时间:2015-11-22 19:09:42

标签: python csv python-3.x dictionary

我想从csv文件(psc.csv)中读取,该文件有两列,如下所示:

cellname,scrambling
UER1100A,128
UER1100B,129
UER1100C,130
UER1300A,1
UER1300B,2
UER1300C,3
UER1400H,128

并将整个文件放入一个字典中,以便字典看起来像:

{'UER1100A': '128' , 'UER1100B': '129' , 'UER1100C': '130' ,  ...}

我尝试使用csv模块,如下所示,但它返回一个混合输出和分离的词典。解决方案是什么?
MyCode:

#!/usr/bin/python3
import csv
with open('psc.csv', newline='') as pscfile:
    reader = csv.DictReader(pscfile)
    for row in reader:
        print(row)

1 个答案:

答案 0 :(得分:3)

只需将每行添加到字典中:

dict()

我不是使用import csv with open('psc.csv',newline='') as pscfile: reader = csv.reader(pscfile) next(reader) results = dict(reader) # pull in each row as a key-value pair ,而是在此处使用常规<directive dataset="dataObject"></directive> ,并在跳过第一行后直接将结果提供给var oldData = ''; var initFunction = function(){ oldData = scope.dataObject; } scope.reset = function(){ scope.dataObject = oldData; }; 调用:

const
  OBr: array [1 .. 5{6}]   of string = ('(', '[', '/*', '<!', '<<'{, 'begin'});
  CBr: array [11 .. 15{16}] of string = (')', ']', '*/', '!>', '>>'{, 'end'});