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>You can use pandas to write your csv (you could actually use pandas for the whole problem), this will automatically transpose you data from a dict of columns to a list of rows:</p>

<pre><code>import pandas as pd
df = pd.DataFrame(newcsvdict)
df.to_csv('new.csv', index=False)
</code></pre>

python