【问题标题】:Reading CSV data from a file into a dictionary从文件中读取 CSV 数据到字典中
【发布时间】:2023-01-08 23:09:46
【问题描述】:

我正在尝试从 CSV 文件创建字典。 csv 文件的第一列包含唯一键,第二列包含值。 csv 文件的每一行代表字典中唯一的键值对。我尝试使用 csv.DictReader 和 csv.DictWriter 类,但我只能弄清楚如何为每一列生成一个新字典。我想要一本字典。这是我尝试使用的代码:

def 读取数据(文件名): 数据 = {} 用 open(file_name, "r") 作为 f: reader = csv.reader(f, delimiter = ',') number_columns = len(下一个(读者)) 对于范围内的 d (number_columns): column_data, column_name = read_column(file_name, d) 数据[列名] = 列数据 返回数据

我的数据:enter image description here 我的预期结果: enter image description here

【问题讨论】:

    标签: python list function csv dictionary


    【解决方案1】:

    如果您不介意为数据使用二维表而不是键值对,则可以使用 pandas 模块,该模块中有一个名为 to_dict() 的有用函数,可将 CSV 转换为字典。所以这就是一个例子的样子:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      相关资源
      最近更新 更多