Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict to csv in columns format

Tags:

python

csv

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?

like image 561
Dalvtor Avatar asked Mar 28 '26 17:03

Dalvtor


2 Answers

Or you can use Pandas for that, which only takes two lines

import pandas as pd

pd.DataFrame(items).fillna('').to_csv('file_path')
like image 60
Bubble Bubble Bubble Gut Avatar answered Mar 31 '26 08:03

Bubble Bubble Bubble Gut


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,
like image 30
Ajax1234 Avatar answered Mar 31 '26 08:03

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!