python - 将 .csv 导入字典

标签 python csv dictionary

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

.csv 文件看起来像这样:

F59241,GG1212
F65563,QQ434
F59226,WW343
F69215,CC434

我试过的是:

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

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

最佳答案

当您退出 block 时,with 构造关闭文件。您需要首先使用 block 读取 infile 中的数据

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

关于python - 将 .csv 导入字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260538/

相关文章:

python - 如何更改 Pandas 中除第一列以外的所有列的列类型?

python - 如何清除值为 "No"而不是 NaN 的列中的值?

python-3.x - 如何在匹配字符串后直到下一个匹配字符串将文本文件中的行分配给字典

python - 在 Python 中导入 LinkedIn API 时出错

python - 在 macOS 上为 MoviePy 安装 ffmpeg 失败并出现 SSL 错误

python - pip 和安装 mysql-python

Python:我可以在字典中将字符串作为键并将函数作为值吗?

python - 如何从 csv 中读取多行

python - 如何删除除日期列之外所有行均为 NaN 的位置?

python - 引用定义中其他类属性的字典类属性