Create a CSV file from a list of dictionaries in Python


Python tip:

You can use DictWriter to create a CSV file from a list of dictionaries.

An example👇

import csv

users = [
    {"username": "johndoe", "name": "John Doe"},
    {"username": "bob", "name": "Bob Builder"},
    {"username": "daisy", "name": "Daisy Flower"},
]

fieldnames = ["username", "name"]

with open("users.csv", "w") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(users)

"""
users.csv

username,name
johndoe,John Doe
bob,Bob Builder
daisy,Daisy Flower
"""