How to write a list of dictionaries to a CSV file in Python

Writing a list of dictionaries to a CSV file converts the dictionary keys to columns and values to row entries.

Solution for How to write a list of dictionaries to a CSV file in Python : You can use csv.DictWriter to write a list of dictionaries to a CSV file Call open(filename, mode) with mode as “w” to open filename with write access. Call csv.DictWriter(csvfile, keys) with csvfile as the opened file and keys as the dictionarys’ keys to return a DictWriter object. Call DictWriter.writeheader() with DictWriter as the previous result to write the header to the CSV file. Call DictWriter.writerows(rows) with DictWriter as the DictWriter object and rows as the list of dictionaries to write. Use file.close() to close the stream.


how-to-write-a-list-of-dictionaries-to-a-csv-file-in-python