Python dictionary keys to csv file with column match
Question: I'm trying to push multiple dictionaries (keys and values) to a csv file by
matching the key to a column in the csv header. Example:

    
    
    import csv
    d1 = {'a':1, 'b':2, 'c': 3}
    d2 = {'d':4, 'e':5, 'f': 6}
    with open('my_data.csv','wb') as f:
        w = csv.writer(f)
        w.writerow(['a', 'b', 'c', 'd', 'e', 'f'])
    
    #iterate through all keys in d1,d2,dn
    #if key matches column:
        #write value of key to the bottom of column
    #else:
        #error key not found in header
    

expected result in mydata.csv

    
    
    a,b,c,d,e,f
    1,2,3,4,5,6
    


Answer: The answer is.. don't just pass the column names to writerow().. put them in a
variable `columns` and then use that to control the order in which the values
are written out. Python dictionaries have no order.. you have to use a little
bit of code to sort the values into the order you want.

The last line of code, which writes out the values into the CSV, uses a python
feature called List Comprehension. It's a shortcut that saves 3-4 lines of
code. Look it up, they are very handy.

    
    
    import csv
    d1 = {'a':1, 'b':2, 'c': 3}
    d2 = {'d':4, 'e':5, 'f': 6}
    
    columns = ['a', 'b', 'c', 'd', 'e', 'f']
    
    # combine d1 and d2 into data.. there are other ways but this is easy to understand
    data = dict(d1)
    data.update(d2)
    
    with open('my_data.csv','wb') as f:
        w = csv.writer(f)
        w.writerow(columns)
        # make a list of values in the order of columns and write them
        w.writerow([data.get(col, None) for col in columns])
    

Here is what it would look like without the list comprehension:

    
    
        row = []
        for col in columns:
            row.append(data.get(col, None)) 
        w.writerow(row)
    

