我正在为一个班级做一个程序,我们的老师给了我们使用的csv.DictReader函数,但没有解释它。它只是一个更大的计划的一部分。我正在尝试阅读天气数据的电子表格。它有几个名为TemperatureF,VisibilityMPH等的列。我需要在电子表格的一列中读取并将其值作为列表放入字典中,其中键是列名。我这样做了,但是当我尝试循环并为第二列进行操作时,我的列表没有填满。这是我的代码和输出。
import csv
def read_file(filename, col_list):
with open(filename, 'r') as f:
reader = csv.DictReader(f)
final_dict = {}
x = 0
while x < len(col_list):
print 'X IS ' + str(x)
this_list = []
print 'list before adding stuff: ' #test
print this_list #test
for row in reader:
this_list.append([row[col_list[x]]])
print 'list after adding stuff' #test
print this_list #test
final_dict[col_list[x]] = this_list
x += 1
print final_dict
def main():
read_file('weather.csv', ['VisibilityMPH', 'TemperatureF'])
if __name__ == "__main__":
main()
输出:
答案 0 :(得分:0)
你可能想要的是:
import csv
def read_file(filename, col_list):
with open(filename, 'r') as f:
reader = csv.DictReader(f)
final_dict = {}
x = 0
while x < len(col_list):
print 'X IS ' + str(x)
this_list = []
print 'list before adding stuff: ' #test
print this_list #test
for row in reader:
this_list.append([row[col_list[x]]])
print 'list after adding stuff' #test
print this_list #test
final_dict[col_list[x]] = this_list
x += 1
print final_dict
def main():
read_file('weather.csv', ['VisibilityMPH', 'TemperatureF'])
if __name__ == "__main__":
main()
注意你的while块有不正确的缩进。但实际上可以改进代码片段。
import csv
def read_file(filename, col_list):
with open(filename, 'r') as f:
reader = csv.DictReader(f)
final_dict = { col_name: [] for col_name in col_list }
for row in reader:
for col_name in col_list:
final_dict[col_name].append(row[col_name])
print final_dict
def main():
read_file('weather.csv', ['VisibilityMPH', 'TemperatureF'])
if __name__ == "__main__":
main()