-1

I've dictionary in this format:

d = {'key_1':['item_1','item_2','item_3'],'key_2':['item_1','item_2','item_3'],}

And I need to save it in csv format.

I did this:

import csv

with open('output.csv', 'w') as f: 
    w = csv.DictWriter(f, d.keys())
    w.writeheader()
    w.writerow(d)

But I get only one row for the header and one more row for the items, I want each item in a different row as what you get with pandas.

df = pd.DataFrame(d)
df.to_csv('output.csv')

But of course in this case without using pandas.

Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

1 Answers1

3

This program does what you want, assuming that len(d['key_1']) == len(d['key_2']).

import csv

d = {
    'key_1':['item_1','item_2','item_3'],
    'key_2':['2_item_1','2_item_2','2_item_3'],
}

with open('output.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(d.keys())
    w.writerows(zip(*d.values()))

Result:

key_1,key_2
item_1,2_item_1
item_2,2_item_2
item_3,2_item_3

If the value lists might be of varying length, try this:

import csv
import itertools

d = {
    'key_1':['item_1','item_2','item_3'],
    'key_2':['2_item_1','2_item_2','2_item_3', '2_item_4'],
}

with open('output.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(d.keys())
    w.writerows(itertools.izip_longest(*d.values()))

Result:

key_1,key_2
item_1,2_item_1
item_2,2_item_2
item_3,2_item_3
,2_item_4
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • what it does the '*' in itertools.izip_longest(*d.values()) ? – Luis Ramon Ramirez Rodriguez Mar 16 '16 at 16:31
  • 1
    @LuisRamonRamirezRodriguez - see http://stackoverflow.com/questions/5917522/unzipping-and-the-operator http://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean-in-python https://bytes.com/topic/python/answers/35395-voodoo-zip-somelist – Robᵩ Mar 16 '16 at 18:18