如何从CSV文件创建具有一个键和多个值的字典?

时间:2019-05-16 02:38:25

标签: python csv dictionary

我正在尝试从CSV文件创建字典。 CSV文件的第一列包含唯一的代码/键,并且由于第二列包含值。 CSV文件的每一行代表一个唯一的键。

我尝试使用csv.DictReadercsv.DictWriter类,但是我只能弄清楚如何为每一行生成一个新的字典。

这是我的代码的一部分:

import csv

with open('input_experiment.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('input_experiment.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    for rows in reader:
        k = rows[0]
        v = rows[1]
        mydict = {k:v for k, v in rows}
    print(mydict)

这是我的数据的样子:

第一列是关键,我想为每一行创建一个字典

EOLB-98      2  4   3   1   4   4   CCPZ-81 CTCB-18 VBOX-39

LKHN-41      3  3   1   1   4   3   BYAP-21 QENC-92 JSZQ-42

NWVF-51      5  3   2   4   3   5   YWVL-18 KPCC-99 FIMD-24

XVGP-15      1  4   1   1   4   1   DZCP-35 WMBB-45 XTCH-99

2 个答案:

答案 0 :(得分:0)

如果您希望它可以访问每个键的特定值,则可以考虑将列表作为每个键的值。

import csv

with open('input_experiment.csv', mode='r') as infile:
    reader = csv.reader(infile)

    # Not sure why you have the next two lines
    with open('input_experiment.csv', mode='w') as outfile:
        writer = csv.writer(outfile)

    mydict = {}
    for row in reader:
        mydict[row[0]] = row[1:]
    print(mydict)

答案 1 :(得分:0)

csv.DictReader默认情况下将第一行作为字典的键,因此在这里将不起作用,因为您希望将第一列作为键。

因此,您可以使用csv.reader读取csv文件,然后遍历行并使用字典理解功能来创建字典

import csv

mydict = {}

#Open the file in read mode
with open('input_experiment.csv', mode='r') as infile:
    #Open a reader to the csv, the delimiter is a single space
    reader = csv.reader(infile, delimiter=' ', skipinitialspace=True)

    #Read into the dictionary using dictionary comprehension, key is the first column and row are rest of the columns
    mydict = { key: row for key, *row in reader }

print(mydict)

所以如果输入文件是

EOLB-98 2 4 3 1 4 4 CCPZ-81 CTCB-18 VBOX-39
LKHN-41 3 3 1 1 4 3 BYAP-21 QENC-92 JSZQ-42
NWVF-51 5 3 2 4 3 5 YWVL-18 KPCC-99 FIMD-24
XVGP-15 1 4 1 1 4 1 DZCP-35 WMBB-45 XTCH-99

输出将为

{'EOLB-98': ['2', '4', '3', '1', '4', '4', 'CCPZ-81', 'CTCB-18', 'VBOX-39'], 
'LKHN-41': ['3', '3', '1', '1', '4', '3', 'BYAP-21', 'QENC-92', 'JSZQ-42'], 
'NWVF-51': ['5', '3', '2', '4', '3', '5', 'YWVL-18', 'KPCC-99', 'FIMD-24'], 
'XVGP-15': ['1', '4', '1', '1', '4', '1', 'DZCP-35', 'WMBB-45', 'XTCH-99']}
相关问题