Python Dictionary to CSV

后端 未结 6 769
情深已故
情深已故 2020-11-27 16:09

I have written code to read a CSV into a python dictionary, which works fine. I\'m trying to get the dictionary back to a CSV. I have written the following:

         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 16:48

    d = [{'a': 1, 'b': 2},{'a': 3, 'b': 4}]
    
    with open('csv_file.csv', 'w', newline='\n') as f:
        w = csv.DictWriter(f, d[0].keys())
        w.writeheader()
        for i in d:
            w.writerow(i)
    

    gets you

    a,b
    1,2
    3,4
    

提交回复
热议问题