【问题标题】:How to create a dictionary with one key and multiple values from a CSV file?如何从 CSV 文件创建具有一个键和多个值的字典?
【发布时间】:2019-05-16 02:38:24
【问题描述】:

我正在尝试从 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

【问题讨论】:

  • 请在代码方面添加您迄今为止尝试过的内容
  • 谢谢我最近用所有信息上传了我的问题
  • 请复制粘贴csv的内容并将其添加到问题中
  • 谢谢@DiegoSebastianRamirezRamire 我在下面添加了一个关于如何实现您所寻找的答案的答案。请检查!

标签: python csv dictionary


【解决方案1】:

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']}

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

    • 一个更pythonic的方式是说mydict = { key: row for key, *row in reader }
    猜你喜欢
    • 2017-05-01
    • 2021-04-13
    • 2015-07-25
    • 2022-11-26
    • 1970-01-01
    • 2019-10-30
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多