Hi I am trying to create a CSV table of stocks that will look like this (the numbers are set to be the same for the sake of simplicity):
symbol ev_ebitda asset
msft 40 60
cvx 40 60
baba 40 60
I have a list of stock symbols (which will be expanded at a later point in time):
symbol = ["msft", "cvx", "baba"]
I created a dictionary for each symbol with 'symbol'
,'ev_ebitda'
, and 'asset'
as keys:
i=0
while i <len(symbol):
vars()[symbol[i]] = {}
vars()[symbol[i]]['symbol']=symbol[i]
vars()[symbol[i]]['ev_ebitda'] = 40
vars()[symbol[i]]['asset'] = 60
i +=1
So for example:
cvx = {'asset': 60, 'ev_ebitda': 40, 'symbol': 'cvx'}
Then I attempted to output the table with the following code:
header = ["symbol","ev_ebitda","asset"]
f = open('output.csv', 'wb')
w =csv.DictWriter(f, fieldnames = header)
w.writeheader()
w.writerow() #not sure what to put in here
I am not sure how to write multiple rows from multiple dictionaries. I tried following the the methods from this discussion, but had no success. I have been trying to solve the problem the past 8 hours and would much appreciate your help! Here is my complete code:
import csv
symbol = ["msft", "cvx", "baba"]
header = ["symbol","ev_ebitda","asset"]
#create dictionary from the symbol list
i=0
while i <len(symbol):
vars()[symbol[i]] = {}
vars()[symbol[i]]['symbol']=symbol[i]
vars()[symbol[i]]['ev_ebitda'] = 40
vars()[symbol[i]]['asset'] = 60
i +=1
#output csv
f = open('output.csv', 'wb')
w =csv.DictWriter(f, fieldnames = header)
w.writeheader()
w.writerow(cvx)