【问题标题】:How to format a list of dictionaries from CSV? - Python如何从 CSV 格式化字典列表? - Python
【发布时间】:2018-03-07 02:15:15
【问题描述】:

我有一个股票价格数据的 CSV 文件,我想将它放入包含日期和收盘价的字典中。

这是 CSV 的样子: date close volume open high low 2017/09/22 151.89 46575410 152.02 152.27 150.56 2017/09/21 153.39 37350060 155.8 155.8 152.75 2017/09/20 156.07 52126240 157.9 158.26 153.83 2017/09/19 158.73 20565620 159.51 159.77 158.44

我希望最后的字典是这样排列的:

perfect_dict = [
{'Date': '2017/09/22', 'Close': '151.89'},
{'Date': '2017/09/21', 'Close': '153.39'},
...]

我当前的代码获取 CSV 数据并为日期和收盘价创建两个单独的列表。我试过使用dict(zip(dates, close_prices),但这并没有按照我上面提到的方式格式化新字典。这是我的代码:

import csv
from collections import defaultdict

# --->
columns = defaultdict(list)

with open('mydata.csv') as f:
    reader = csv.DictReader(f) 
    for row in reader: value2,...}
        for (k,v) in row.items(): 
            columns[k].append(v) 

dates = columns['date']
close_prices = columns['close']

# This is what doesn't format it right
#stock_dict = dict(zip(dates, close_prices))
#pprint.pprint(stock_dict)

如果有人能指出我正确的方向,那就太棒了,谢谢!

【问题讨论】:

  • 我有一个问题。为什么你的逗号分隔值文件没有用逗号分隔?
  • 有两件事是错误的。您期望字典作为输出。但是,没有与每个子词典关联的键。此外,您在 csv 文件中没有逗号。
  • @HyperNeutrino 我明白你的意思,哈哈。这些数据只是复制了一个 Google 电子表格,这就是原因

标签: python python-3.x csv dictionary stockquotes


【解决方案1】:

可能有点晚了,但您可以尝试使用“普通” csv 阅读器的以下解决方案并稍后转换数据:

columns = list()
with open('mydata.csv') as f:
    reader = list(csv.reader(f))
    header = reader[0]
    for row in reader[1:]:
        temp_dict = dict()
        for idx, item in enumerate(row):
            if idx < 2:
                temp_dict[header[idx]] = item
        columns.append(new_dict)

假设您的 csv 结构与您呈现的一样(标题为第一行,列的顺序),代码会将原始 csv 输入转换为字典列表。 此外,idx &lt; 2 确保只有“日期”和“关闭”映射到新输出。
如果您更喜欢大写的列标题,只需在第 4 行后添加 header = list(map(lambda x: x.capitalize(), header))

【讨论】:

    【解决方案2】:

    我认为您的目标格式是不可能的 - 您的意思是说您想要一个字典列表吗?正如所写,这是一个字典字典,但外部字典没有任何键。

    此外,如果您想为给定的字典键设置值,您可能需要执行以下操作:

    columns[k] = v
    

    编辑:

    这是否更接近您正在寻找的内容?将列实例化为空列表,然后将 csv 的每一行格式化为字典并附加到该列表。

    columns = []
    
    with open('mydata.csv') as f:
        reader = csv.DictReader(f) 
        for row in reader:
            row_as_dict = {k: v for k, v in row.items()}
                columns.append(row_as_dict) 
    

    【讨论】:

    • 我认为字典列表会更好,是的。我不知道那会是什么样子,但我只希望每个日期及其对应的收盘价都是构成整体列表的单个实体。这可能吗?
    • 添加了其他信息。输出现在应该更像:list_of_dicts = [ {'Date': '2017/09/22', 'Close': '151.89'}, {'Date': '2017/09/21', 'Close': '153.39'}, ...]
    • 我运行了你在底部添加的代码,它返回错误:columns[k].append(row_as_dict) NameError: name 'k' is not defined
    • 抱歉,只需要删除 [k] - 请参阅更新的答案。
    【解决方案3】:

    通过使用pandas 读取csv file

    • 先读取dateclose列并存储为列表
    • 比列出我们需要的字典格式。

    代码

    import pandas as pd
    df = pd.read_csv("file_name.csv")
    # read the date and close column and store as a list.
    time_list = list(df['date'])
    close_list = list(df['close'])
    perfect_dict = []
    # here take the minimum length
    # because avoiding index error
    take_length = min(len(time_list),len(close_list))
    for i in range(take_length):
        temp_dict={}
        temp_dict["Date"]=time_list[i]
        temp_dict["Close"] = close_list[i]
        perfect_dict.append(temp_dict)
    print(perfect_dict)
    

    另一种可能的方式。

    import csv
    perfect_dict=[]
    with open('file.csv') as f:
        reader = list(csv.reader(f))
        for row in reader[1:]:
            temp_dict = {}
            temp_dict["Date"] = row[0]
            temp_dict["Close"] = row[1]
            perfect_dict.append(temp_dict)
    print(perfect_dict)
    

    【讨论】:

      【解决方案4】:

      您可以使用字典理解:

      import csv
      
      data = list(csv.reader(open('filename.csv')))
      final_data = [{a:b for a, b in zip(["Date", "Close"], i[:2])} for i in data[1:]]
      

      请注意,您不能将字典存储在集合中,因为字典本身是不可散列的。

      【讨论】:

      • 这不起作用;它只是列出了从"Date" 到该行的映射列表作为字符串。对 OP 没有帮助...编辑我认为我的 CSV 不是逗号分隔的...抱歉
      • @HyperNeutrino 不,这应该可以。 OP 要求使用此代码创建的键“日期”和“关闭”创建字典列表。但是,如果有我没有看到的明显语法错误,请告诉我。
      猜你喜欢
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2021-12-06
      • 2015-12-24
      • 1970-01-01
      • 2016-08-02
      相关资源
      最近更新 更多