How to write a dictionary to a .csv in Python

A .csv file is a file type containing values separated by commas and newlines. Writing a dictionary to a .csv file writes each key-value pair separated by a comma and to a new line in the .csv file.

Solution for How to write a dictionary to a .csv in Python : You can use csv.writer.writerow() to write a dictionary to a .csv file Use open(file, mode) with “w” as mode to open a stream of a .csv file file for writing. Call csv.writer(csvfile) with this stream as csvfile to create a writer object. Use a for-loop and dict.items() to iterate over the keys and values in dict. In each iteration, call csv.writer.writerow(row) with a list of the current key and value as row to write it to the .csv file. Use file.close() to close the file.


how-to-write-a-dictionary-to-a-csv-in-python