将.csv导入字典

gJg*_*gJg 1 python csv dictionary

我正在尝试将.csv文件导入dict.我的麻烦是,当我尝试从dict中读取时,我没有得到输出?为什么??

.csv文件看起来像这样:

F59241,GG1212
F65563,QQ434
F59226,WW343
F69215,CC434
Run Code Online (Sandbox Code Playgroud)

我尝试过的是:

import csv

with open('myfile.csv', mode='r') as infile:
    reader = csv.reader(infile,)
with open('mtfile.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
DICT = {rows[0]:rows[1] for rows in reader}
n = ['F59241', 'F65563', 'F59226', 'F69215']

for key in n:
    if DICT.get(key):
        print ((key) + ' : ' + DICT[key])
    else:
        print((key) + ' : ' + "Not Available")
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?谢谢

She*_*tJS 6

退出块时,with构造将关闭文件.您需要先读取infilewith块内的数据

import csv

with open('myfile.csv', mode='r') as infile:
    reader = csv.reader(infile,)
    DICT = {rows[0]:rows[1] for rows in reader if len(rows) == 2}
    print DICT

n = ['F59241', 'F65563', 'F59226', 'F69215']

for key in n:
    if DICT.get(key):
        print ((key) + ' : ' + DICT[key])
    else:
        print((key) + ' : ' + "Not Available")
Run Code Online (Sandbox Code Playgroud)