简体   繁体   English

从文件中读取 CSV 数据到字典中

[英]Reading CSV data from a file into a dictionary

I am trying to create a dictionary from a CSV file.我正在尝试从 CSV 文件创建字典。 The first column of the csv file contains unique keys and the second column contains values. csv 文件的第一列包含唯一键,第二列包含值。 Each row of the csv file represents a unique key, value pair within the dictionary. csv 文件的每一行代表字典中唯一的键值对。 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 column.我尝试使用 csv.DictReader 和 csv.DictWriter 类,但我只能弄清楚如何为每一列生成一个新字典。 I want one dictionary.我想要一本字典。 Here is the code I am trying to use:这是我尝试使用的代码:

def read_data(file_name):
    data = {}
    with open(file_name, "r") as f:
        reader = csv.reader(f, delimiter = ',')
        number_columns = len(next(reader))
        for d in range (number_columns):
            column_data, column_name = read_column(file_name, d)
            data[column_name] = column_data
    return data

My data: enter image description here My expected result: enter image description here我的数据:在此处输入图像描述我的预期结果:在此处输入图像描述

If you don't mind having a 2D table for you data instead of key-value pairs, you can use the pandas module and in the module is useful funcion called to_dict() that converts a CSV to a dictonary.如果您不介意为您的数据使用二维表而不是键值对,则可以使用 pandas 模块,该模块中有一个名为 to_dict() 的有用函数,可将 CSV 转换为字典。 So this is how an example would look like:所以这就是一个例子的样子:

import pandas as pd

file = pd.read_csv(filename, sep=',') #<---- the sep arguement does the same thing as the delimiter arguement, it is short for seperater

random_dict = pd.to_dict(file)

Using csv DictReader :使用csv DictReader

with open(file_name) as csv_file:
    dictR = csv.DictReader(csv_file)
    data = {hdr: [] for hdr in dictR.fieldnames}
    for row in dictR:
        for field in row:
            data[field].append(row[field])

Build initial data dict using the field names fetched from the DictReader .使用从DictReader获取的字段名称构建初始data dict Then iterate over rows and fields in row.然后遍历行和行中的字段。 For each field append the field value to the list corresponding to the field name in the data dict .对于每个字段 append 字段值到列表中对应于data dict中的字段名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM