我试图从我的.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')
答案 0 :(得分:5)
DictReader是这里的方式:
import csv
with open('summ.csv') as csvfile:
reader = csv.DictReader(csvfile)
kept2 = [row for row in reader]