list - 使用csv生成dict列表

我有一个三列和多行的CSV文件,所有数据都是字符串,我试图一次读取一行CSV,并将每一行转换为一个Dict,然后将它附加到一个列表中,这样我就有了一个Dict列表,

我的代码:


csv_object = s3.Object('MyBucket', 'My.csv')


csv_file = csv_object.get()['Body'].read().decode('utf-8')



f = StringIO(csv_file)


reader = csv.reader(f, delimiter=',')



list_of_json = []


mydevice = {}



for row in reader:


 mydevice["device"] = row[0]


 mydevice["serial"] = row[1]


 mydevice["software"] = row[2]



 list_of_json.append(mydevice)



软件运行(没有错误),但它并不产生期望的结果,如果print(list_of_json)循环完成后,我想要它产生这个;


[{"device":"Dev1","serial":"Ser1","software":"software1"},{.....}]



就像追加语句不存在一样;

 
[]



 

CSV读取和 for row in reader:看起来都很正常。

时间:

你需要在循环中创建一个新字典:


csv_object = s3.Object('MyBucket', 'My.csv')


csv_file = csv_object.get()['Body'].read().decode('utf-8')



f = StringIO(csv_file)


reader = csv.reader(f, delimiter=',')



list_of_json = []



for row in reader:


 mydevice = {}


 mydevice["device"] = row[0]


 mydevice["serial"] = row[1]


 mydevice["software"] = row[2]


 list_of_json.append(mydevice)



为什么不直接使用csv.DictReader


csv_object = s3.Object('MyBucket', 'My.csv')


csv_file = csv_object.get()['Body'].read().decode('utf-8')



f = StringIO(csv_file)


reader = csv.DictReader(f, ('device', 'serial', 'software'))


list_of_json = [dict(device) for device in reader]



...