convert csv file to list of dictionaries

前端 未结 6 1366
我寻月下人不归
我寻月下人不归 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条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 19:42

    Using the csv module and a list comprehension:

    import csv
    with open('foo.csv') as f:
        reader = csv.reader(f, skipinitialspace=True)
        header = next(reader)
        a = [dict(zip(header, map(int, row))) for row in reader]
    print a    
    

    Output:

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

提交回复
热议问题