convert csv file to list of dictionaries

前端 未结 6 1353
我寻月下人不归
我寻月下人不归 2020-12-04 19:01

I have a csv file

col1, col2, col3
1, 2, 3
4, 5, 6

I want to create a list of dictionary from this csv.

output as :



        
6条回答
  •  Happy的楠姐
    2020-12-04 19:58

    Use csv.DictReader:

    import csv
    
    with open('test.csv') as f:
        a = [{k: int(v) for k, v in row.items()}
            for row in csv.DictReader(f, skipinitialspace=True)]
    

    Will result in :

    [{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}]
    

提交回复
热议问题