'How to write CSV from a list of dictionaries
I found a lot of posts about going from CSV to a list of dictionaries but not the other way around. I'm trying to write a csv file from a list of dictionaries, within each dictionary the keys are the same and there are equal number of pairings per dictionary. How would I go about using the keys for the header row?
edit: yes I've read the adam smith page with the DictWriter unfortunately, I don't know the key names ahead of time just that the names are the same across all dictionaries in the list.
ie. [{A:1,B:2},{A:3,B:4}] into...
A,B
1,2
3,4
import csv
def function(list_of_dic,csvFileName):
with open(list_of_dic,'w') as f:
writer = csv.DictWriter(f)
Solution 1:[1]
import pandas as pd
data = [{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
df = pd.DataFrame(data)
df = pd.DataFrame.from_dict(data)
df = pd.DataFrame.from_records(data)
df.to_csv("Filename.csv")
output:
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
Solution 2:[2]
The DictWriter doc has a good example. Assuming you know the key names in advance, you use those as the fieldnames. And since you already have a list of dicts, writerows will consume them all.
import csv
def function(list_of_dic,csvFileName):
with open(list_of_dic,'w') as f:
writer = csv.DictWriter(f, fieldnames=["A", "B", "C"])
writer.writeheader()
writer.writerows(list_of_dic)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raj Patel |
| Solution 2 | tdelaney |
