0

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)   
Community
  • 1
  • 1
Vic
  • 617
  • 1
  • 8
  • 12

1 Answers1

0

As you are using DictWriter, you would need to construct a per row dictionary as follows:

import csv

symbol = ["msft", "cvx", "baba"]
header = ["symbol","ev_ebitda","asset"]

with open('output.csv', 'wb') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames=header)
    csv_output.writeheader()

    for s in symbol:
        row = {'asset': 60, 'ev_ebitda': 40, 'symbol': s}
        csv_output.writerow(row)

This will create you an output CSV file as follows:

symbol,ev_ebitda,asset
msft,40,60
cvx,40,60
baba,40,60
Martin Evans
  • 45,791
  • 17
  • 81
  • 97