I have the following dict
items = {'people': ['Peter', 'Danny'], 'numbers': [1,2,3,4], 'cities': ['London']}
And I would like to write that dict to a CSV file by columns, that is, with the following format:
people,numbers,cities
Peter,1,London
Danny,2,
,3,
,4,
My current approach won't work because I get the CSV file by rows:
people,Peter,Danny
numbers,1,2,3,4
cities,London
How can I do what I need?
Or you can use Pandas for that, which only takes two lines
import pandas as pd
pd.DataFrame(items).fillna('').to_csv('file_path')
You can use itertools.zip_longest (itertools.izip_longest in Python2):
from itertools import zip_longest
import csv
items = {'people': ['Peter', 'Danny'], 'numbers': [1,2,3,4], 'cities': ['London']}
headers = ['people', 'numbers', 'cities']
with open('filename.csv', 'w') as f:
full_listing = [['' if not b else b for b in i] for i in zip_longest(*[items[c] for c in headers])]
write = csv.writer(f)
write.writerows([headers]+full_listing)
Output:
people,numbers,cities
Peter,1,London
Danny,2,
,3,
,4,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With