我想从csv文件中导入它。
task_name time_spent notes date task_number
Worked on hotfrog. 45 Hotfrog started glitching so I moved on to something else. 01/25/2017 02:25 1
falkd 3 adlskfj 01/01/2005 09:40 2
并将其转换为一个列表,其中包含字典,如下所示:`
self.example_dict_list =
[{'task_name': 'Worked on hotfrog', 'time_spent': '45', 'notes': 'Hotfrog started glitching so I moved on to something else', 'date': '01/25/2017 02:25', 'task_number': '1'}, {'task_name': 'falkd', 'time_spent': '3', 'notes': 'adlskfj', 'date': '01/01/2005 09:40', 'task_number': '2'}]
答案 0 :(得分:1)
这应该有用,我制作了一个小CSV
文件,看起来像这样:
task_name time_spent notes date task_number
worked on blah 45 glitching and stuff 1/1/15 2
stuff 40 stuff happened 2/3/16 5
然后将它转换为dicts列表,你会这样做:
import csv
f = 'path_to_file.csv'
with open(f, 'r') as fin:
reader = csv.reader(fin)
headers = reader.next()
dict_list = []
for line in reader:
dict_list.append(dict(zip(headers, line)))
dict_list
[{'date': '1/1/15',
'notes': 'glitching and stuff',
'task_name': 'worked on blah',
'task_number': '2',
'time_spent': '45'},
{'date': '2/3/16',
'notes': 'stuff happened',
'task_name': 'stuff',
'task_number': '5',
'time_spent': '40'}]