How can I save a dictionary to a file in this situation?

import csv w = csv.writer(open("un.csv", "w")) a = [ {"name": "Tom", "age": 10, "city": "Moscow"}, {"name": "Mark", "age": 5, "city": "Khabarovsk"}, {"name": "Pam", "age": 7, "city": "Sahalin"} ] for key, val in a.items(): w.writerow([key, val]) 
  • one
    Make it a list - the dictionary keys are the names of the columns, and the values ​​of the dictionary are the row cells - gil9red
  • And what prevents to make a nested list? - Sithell Nov.

2 answers 2

You can do this:

 import csv data = [ {"name": "Tom", "age": 10, "city": "Moscow"}, {"name": "Mark", "age": 5, "city": "Khabarovsk"}, {"name": "Pam", "age": 7, "city": "Sahalin"} ] with open("file.csv", "wb") as csv_file: csv_writer = csv.writer(csv_file) # write column names csv_writer.writerow(data[0].keys()) # iterate over data dicts and write values for dict_item in data: csv_writer.writerow(dict_item.values()) 

Contents of file.csv :

 city,age,name Moscow,10,Tom Khabarovsk,5,Mark Sahalin,7,Pam 

    You can use csv.DictWriter :

     #!/usr/bin/env python3 import csv people = [ {"name": "Tom", "age": 10, "city": "Moscow"}, {"name": "Mark", "age": 5, "city": "Khabarovsk"}, {"name": "Pam", "age": 7, "city": "Sahalin"} ] with open('people.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames=people[0]) writer.writeheader() writer.writerows(people) 

    people.csv

     name,age,city Tom,10,Moscow Mark,5,Khabarovsk Pam,7,Sahalin