How to write a dict to a csv
<p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the next column next the the first name. Thanks for your time.</p>

<p>Code:
    import csv</p>

<pre><code>with open('fullnames.csv','r') as f:
reader = csv.reader(f)
newcsvdict = {"first name": [], "last name": []}
for row in reader:
    first = row[0].split()[0]
    last = row[0].split()[1]
    newcsvdict["first name"].append(first)
    newcsvdict["last name"].append(last)


with open('new.csv','w') as f:
w = csv.DictWriter(f, newcsvdict.keys())
w.writeheader()
w.writerow(newcsvdict)
</code></pre>

<p>Output:
<a href="http://i.stack.imgur.com/5cOcI.png" rel="nofollow"><img src="http://i.stack.imgur.com/5cOcI.png" alt="enter image description here"></a></p>

<p>In this simple case there is little benefit in using a <code>csv.DictWriter</code>, just use <code>csv.writer</code>:</p>

<pre><code>import csv

header = ['first name', 'last name']
with open('fullnames.csv', 'r') as infile, open('new.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(header)
    writer.writerows(row[0].split() for row in csv.reader(infile))
</code></pre>

<p>This works fine provided that the name column in the input CSV always consists of exactly one first name and one surname separated by whitespace. However, if there can be double-barrelled surnames, e.g. Helena Bonham Carter, you need to be more careful about splitting the name. This might work:</p>

<pre><code>row[0].split(' ', 1)
</code></pre>

<p>but it assumes that the separator is exactly one space.</p>

python