user4758796
user4758796

Reputation:

adding dictionary to csv file

My dictionary is as follows:

my_d ={'2010-01-02': [0.696083, 0.617865], '2010-01-01': [0.697253, 0.618224], '2010-01-03': [0.696083, 0.617865]}

and i wish to output like the following:

DATE,EUR,GBP
2010-01-02,0.696083,0.617865
2010-01-03,0.697253,0.618224
2010-01-03,0.696083,0.617865

i have tried this:

my_list = ["date", "EUR", "GBP"]
with open(fname, 'w',newline = '') as my_csv:
csv_writer = csv.writer(my_csv, delimiter=',')
csv_writer.writerow(my_list)
csv_writer.writerows(my_d)

but the csv file looks nothing like that. Please also be aware further up in my code the user has the ability to choose how many values each key has, so in this example it has two, in another it may have three this would also mean my_list would increase in size, but i believe the first row will already cater for that, i just need help with the rest of the rows, i need it to work for any amount of keys.

Upvotes: 2

Views: 67

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

You need to loop over your dictionary items and then write to your file,also its better to use csv module for dealing with csv files :

my_list = ["date", "EUR", "GBP"]
import csv
my_d ={'2010-01-02': [0.696083, 0.617865], '2010-01-01': [0.697253, 0.618224], '2010-01-03': [0.696083, 0.617865]}
with open('fname.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(my_list)
    for mydate in sorted(my_d.keys()):
        spamwriter.writerow([mydate]+my_d[mydate])

Note the absence of newline='' when opening the file. This allows the file to have "normal" newline characters (usually '\n' or '\r\n')

Note that as you are in python 3.x you can open the file with w mode!

Upvotes: 1

Related Questions