Reputation: 595
I have a python dictionary that looks like the following:
{
key1: [value1, value2, value3, n],
key2: [value1, value2, value3, n],
key3: [value1, value2, value3, n],
key4: [value1, value2, value3, n]
}
I would like to write these values to a csv file in the format where each line contains Keys as header and associated values(row by row) under that key.
Upvotes: 1
Views: 11145
Reputation: 1510
Perhaps pandas
can provide you with a more direct way of achieving this, but if you simply want to rely on the csv
package from the standard library, the following naive approach should do:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
data = {
'key1': ['value1', 'value2', 'value3', 'n'],
'key2': ['value1', 'value2', 'value3', 'n'],
'key3': ['value1', 'value2', 'value3', 'n'],
'key4': ['value1', 'value2', 'value3', 'n']
}
header = data.keys()
no_rows = len(data[list(header)[0]])
with open('out.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(header)
for row in range(no_rows):
csvwriter.writerow([data[key][row] for key in header])
This results in
key1,key2,key3,key4
value1,value1,value1,value1
value2,value2,value2,value2
value3,value3,value3,value3
n,n,n,n
Hope this helps!
EDIT
Since this is now the accepted answer, I feel that I should add that pandas.DataFrame.to_csv
does indeed provide a more direct way of achieving this, as mentioned in other answers:
import pandas as pd
pd.DataFrame(data).to_csv('out.csv', index=False)
produces the same output as above (possibly with different line terminators, depending on your system).
Upvotes: 3
Reputation: 422
pandas
provides a very straight forward solution to the problem -
import pandas as pd
df = pd.DataFrame({
'key1': ['value1', 'value2', 'value3', 'n'],
'key2': ['value1', 'value2', 'value3', 'n'],
'key3': ['value1', 'value2', 'value3', 'n'],
'key4': ['value1', 'value2', 'value3', 'n']
})
df.to_csv('/path/to/file')
Upvotes: 3