【问题标题】:Creating a dictionary from a csv file while iterating through rows在遍历行时从 csv 文件创建字典
【发布时间】:2016-03-03 00:26:24
【问题描述】:

我需要创建一个将 csv 文件作为输入并生成字典的函数。输入到函数中的 csv 文件可以具有不同的行数和列数。该函数应该能够对此进行补偿。

可以使用的 csv 文件示例如下:

book.title,book.year,book.author

Godel Escher Bach, 1979, Douglas Hofstadter

What if?, 2014, Randall Munroe

Thing Explainer, 2015, Randall Munroe

Alan Turing: The Enigma, 2014, Andrew Hodges

我需要将 csv 文件第一行中的每个项目作为字典中的一个键,然后将该键下的行中的每个项目放入值列表中。

所以给出的示例 csv 文件的输出将是:

my_dict = { 'book.title': [Godel Escher Bach, What if?, Thing Explainer, Alan Turing: The Enigma,], 'book.year': [1979, 2014, 2015, 2014], 'book.author': [Douglas Hofstadter, Randall Munroe, Randall Munroe, Andrew Hodges]}

【问题讨论】:

  • 到目前为止你想到了什么,你在哪里卡住了?

标签: python csv dictionary iteration row


【解决方案1】:

尝试defaultdict和dictreader读取csv文件-

import csv
from collections import  defaultdict
data = defaultdict(list)


with open(r"C:\bk.csv",'rb') as f:
    rd = csv.DictReader(f)
    for i in rd:
        for j in i.keys():
            data[j].append(i[j])
print {k:v for k,v in data.items()}

输出-

{'book.year': ['1979', '2014', '2015', '2014'], 'book.title': ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma'], 'book.author': [' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']}

注意我假设 csv 文件中没有空白行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 2011-10-08
    • 2012-12-15
    • 2012-01-02
    • 2016-11-22
    相关资源
    最近更新 更多