convert csv file to list of dictionaries

前端 未结 6 1348
我寻月下人不归
我寻月下人不归 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 20:01

    Well, while other people were out doing it the smart way, I implemented it naively. I suppose my approach has the benefit of not needing any external modules, although it will probably fail with weird configurations of values. Here it is just for reference:

    a = []
    with open("csv.txt") as myfile:
        firstline = True
        for line in myfile:
            if firstline:
                mykeys = "".join(line.split()).split(',')
                firstline = False
            else:
                values = "".join(line.split()).split(',')
                a.append({mykeys[n]:values[n] for n in range(0,len(mykeys))})
    

提交回复
热议问题