【问题标题】:Create lists of dictionaries from .CSV file using header words as keys使用标题词作为键从 .CSV 文件创建字典列表
【发布时间】:2015-06-13 20:16:02
【问题描述】:

我正在尝试从我的 .csv 文件创建字典列表。我想将文件的第一行作为字典键,并将它们下面的相应值作为它们的值。这已使用 .txt 文件成功完成,并且运行良好。当我尝试使用 .csv 格式执行此操作时,我遇到了无法调用特定键的问题,因此我认为它无法正常工作。

newqstars = [meteor['M_P'] for meteor in kept2]

>>>KeyError: 'M_P'

我整天都在尝试其他方法,例如 DictReader() 和 csv.reader() 但它们不起作用,所以我只想问我如何修改下面的内容以处理 . .csv

def example_05(filename):


    with open(filename,'r') as file : data = file.readlines()
    header, data = data[0].split(), data[1:] 

    #................ convert each line to a dict, using header 
    # words as keys

    global kept2 
    kept2 = []

    for line in data :
        line = [to_float(term) for term in line.split()]
        kept2.append( dict( zip(header, line) ) )

if __name__ == '__main__' :

    example_05('Geminids.csv')

【问题讨论】:

标签: python list csv dictionary


【解决方案1】:

DictReader 是这里的方法:

import csv

with open('summ.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    kept2 = [row for row in reader]

【讨论】:

  • 那么简单。谢谢!
猜你喜欢
  • 2015-09-16
  • 2018-09-26
  • 2022-01-14
  • 2021-02-19
  • 2016-08-19
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多