【问题标题】:How to create a dictionary from a CSV file, appending multiple values to three keys?如何从 CSV 文件创建字典,将多个值附加到三个键?
【发布时间】:2022-11-26 23:13:03
【问题描述】:

我需要能够将 CSV 文件中的多个值附加到具有三个键的字典中。密钥是 morningmiddaynight。这些值应该来自CSV 文件的每一行。

理想情况下,它应该如下所示。

我无法使用 numpycsv 模块,因此这些选项不可用。它必须在没有导入的情况下工作,我不确定字典以及如何处理它以获得我需要的输出。

这是 CSV 文件的示例:

{
    'morning': {[5, 5, 10, 17, 20, 21]},
    'midday': {[10, 20, 25, 15, 8, 3]},
    'night': {[3, 5, 2, 7, 15, 29]}
}

这是我的代码:

time_list = []
time_dict = {}

with open('stats.csv', 'r') as data_file:
    headers = data_file.readline()

    for line in data_file:
        Time, VS = line.split(',')
        time_list.append(int(VS))
        time_dict[Time] = time_dict.get(Time, 0) + int(VS)

附加到列表会产生应有的每个值,即:

[2, 3, 4, 5, 6, 7, 8]

但是对于字典,它不会单独显示它所附加的键的每个值。相反,它将获取每个键的所有值并将它们加在一起。

打印字典显示如下:

{'morning': 2097, 'midday': 1240, 'night': 1533}

我不确定如何处理这个以使字典看起来像下面这样:

{
    'morning':{[5, 5, 10, 17, 20, 21]},
    'midday': {[10, 20, 25, 15, 8, 3]},
     'night': {[3, 5, 2, 7, 15, 29]}
}

注意:我找到的许多答案都使用 csv 模块,不幸的是我不能将其用于此。对于此解决方案,我必须不使用任何进口产品。

【问题讨论】:

  • 快速评论:您的 dict 实际上不是字典,因为您分配给它的值是无效的 Python 语法。也许,你的意思是{'morning': [5, 5, 10, 17, 20, 21], 'midday': [10, 20, 25, 15, 8, 3], 'night': [3, 5, 2, 7, 15, 29]}
  • 是的,这就是我的意思,很抱歉造成混淆

标签: python csv dictionary


【解决方案1】:

如何改变你的策略并这样做:

morning_list= []
midday_list= []
night_list= []
time_dict = dict()

with open("stats.csv", "r") as data_file:
    headers = data_file.readline()

    for line in data_file:
        Time, VS = line.split(",")
        if Time == "morning":
           morning_list.append(int(VS))
        elif Time == "midday":
           midday_list.append(int(VS))
        elif Time == "night":
           night_list.append(int(VS))

time_dict["morning"] = {morning_list}
time_dict["midday"] = {midday_list}
time_dict["night"] = {night_list}

【讨论】:

  • 不幸的是,这会为“无法散列的类型:'list'”产生 TypeError
【解决方案2】:

我会这样做:

import csv 

with open(fn) as csv_in:
    reader=csv.reader(csv_in)
    header=next(reader)
    data={}
    for t,vs in reader:
        data.setdefault(t, []).append(int(vs))

从评论“我不能使用进口”:

with open(fn) as csv_in:
    header=next(csv_in)
    data={}
    for t,vs in (line.split(',') for line in csv_in):
        data.setdefault(t, []).append(int(vs))

使用您的示例数据:

>>> data
{'morning': [21, 5], 'midday': [29, 25], 'night': [10, 10]}

【讨论】:

  • 感谢您的回答,但不幸的是我无法使用 csv 模块。必须在没有进口的情况下完成
  • @wctn2022:见编辑。
  • 我简化了帖子的示例数据,有两列以上,字典中我想要的值在第 8 列,所以我认为这种方法行不通。
【解决方案3】:

一个简单的方法可能如下:

periods = {
    'morning': [],
    'midday': [],
    'night': []
}

with open('stats.csv') as csv:
    # Skip the header line
    _ = csv.readline()

    # Append the values to the corresponding list in the dictionary
    for row in csv:
        period, value = line.strip().split(',')
        periods[period.lower()].append(int(value))

这会将 periods 设置为字典,其中包含每个关键周期的值列表。

如果您不想对句点进行硬编码,并从 CSV 文件中获取它们,那么这也会有所帮助:

periods = {}

with open('stats.csv') as csv:
    # Skip the header line
    _ = csv.readline()

    # Append the values to the corresponding list in the dictionary
    for row in csv:
        period, value = line.strip().split(',')

        if not period.lower() in periods:
            periods[period.lower()] = []

        periods[period.lower()].append(int(value))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多