如何从CSV文件创建具有一个键和多个值的字典? [英] How to create a dictionary with one key and multiple values from a CSV file?

查看:66
本文介绍了如何从CSV文件创建具有一个键和多个值的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a dictionary from a CSV file. The first column of the CSV file contains unique code/ keys and since the second column, there are values. Each row of the CSV file represents a unique key.

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

I tried to use the csv.DictReader and csv.DictWriter classes, but I could only figure out how to generate a new dictionary for each row.

这是我的代码的一部分:

This is a part of my code:

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)

这是我的数据的样子:

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

The first column is the key and I want to create a dictionary with each row

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.DictReader 默认情况下将第一行作为字典的键,因此在这里不起作用,因为您希望将第一列作为键.

csv.DictReader by default takes the first row as the keys of the dictionary, so that won't work here since you want the first column as the keys.

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

So you can read the csv file using csv.reader and then iterate over the rows and create your dictionary using dictionary comprehension

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

这篇关于如何从CSV文件创建具有一个键和多个值的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆