title: Appending dictionary results to csv in python
body: <p>I am looking to append a dictionary I have to a CSV file were I already have a header line
  and if a value doesn't exist I want to write <code>'-999'</code>:</p>
  
  <pre><code>SDict ={T1:'A',T2:'B',T4:'D')
  </code></pre>
  
  <p>where CSV file has header of</p>
  
  <pre><code>T1,T2,T3,T4,T5
  7,8,9,10,11
  </code></pre>
  
  <p>and the expected results are</p>
  
  <pre><code>T1,T2,T3,T4,T5
  7,8,9,10,11
  A,B,-999,D,-999
  </code></pre>
  
  <p>I am trying to do so with the code:</p>
  
  <pre><code>import sys
  import os
  import csv
  
  def GetFileHeader(Fpath):
      i=10
      ResFile=open (Fpath, 'r+')
      HeaderDict={}
      r=csv.reader(ResFile)
      HeaderList = r.next()
      for Header in HeaderList:
          HeaderDict[Header]=i+1
      print HeaderDict
      ResFile.close()
      return HeaderDict
  
  
  Fpath= r'Z:\temp\assaf\S2TTP\S2T_TP\modules\results\Y124\res.csv'
  
  Header= GetFileHeader(Fpath)
  
  with open(Fpath,'rb') as fin:
      dr = csv.DictReader(fin, dialect='excel')
      print dr
      print dr.fieldnames
  # dr.fieldnames contains values from first row of `f`.
  with open(Fpath,'ab+') as fou:
      dw = csv.DictWriter(fou, dialect='excel', fieldnames=dr.fieldnames)
      fieldnames=dr.fieldnames
      for K in fieldnames:
          dw.writerow(Header[k])
  </code></pre>