csv.DictWriter turns a list of dictionaries into CSV rows. You tell it the column names once, and it writes the values of each dictionary in that order.
The program
python
import csv people = [ {"name": "Ada", "city": "London", "score": 95}, {"name": "Linus", "city": "Helsinki, Finland", "score": 87}, {"name": "Grace", "city": "New York", "score": 91}, ] with open("people.csv", "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=["name", "city", "score"]) writer.writeheader() writer.writerows(people) # show what was saved with open("people.csv", encoding="utf-8") as f: print(f.read(), end="")
output
name,city,score Ada,London,95 Linus,"Helsinki, Finland",87 Grace,New York,91
How it works
fieldnamessets the columns and their order.writeheader()writes them as the first line.writerows()writes one line for each dictionary. Numbers such as95are turned into text for you."Helsinki, Finland"contains a comma, so the writer puts quotes around it. That way a CSV reader knows the comma is part of the value.newline=""stops an extra empty line appearing between rows on Windows.
Rows as lists
If your rows are lists instead of dictionaries, use csv.writer and write the header as a normal row:
python
import csv rows = [ ["Hedy", "Vienna", 88], ["Alan", "London", 93], ] with open("people.csv", "w", encoding="utf-8", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "city", "score"]) writer.writerows(rows) with open("people.csv", encoding="utf-8") as f: print(f.read(), end="")
output
name,city,score Hedy,Vienna,88 Alan,London,93
Related programs: Read a CSV file.