[英]Creating a dictionary from a csv file while iterating through rows
我需要創建一個將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]}
嘗試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文件中沒有空白行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.