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)