Reputation: 364
I have a dict like this :
{
'col1': [1, 2, 3],
'col2': [4, 5, 6],
'col3' : [7, 8, 9]
}
and I want a csv like
col1;col2;col3
1;4;7
2;5;8
3;6;9
I try with for
loops but a don't succed to write the values in the right order.
Upvotes: 3
Views: 3237
Reputation: 1
If you use pandas, it will be super easy to write to csv file.
import pandas as pd
data = {
'col1': [1, 2, 3],
'col2': [4, 5, 6],
'col3' : [7, 8, 9]
}
df = pd.DataFrame(data, columns=['col1', 'col2', 'col3'])
df.to_csv('csv_file.csv', sep=';', index=False)
Upvotes: 0
Reputation: 40763
The key here is to transform
data = {
'col1': [1, 2, 3],
'col2': [4, 5, 6],
'col3' : [7, 8, 9]
}
into a list of rows:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
We know that this expression will get a list of columns:
header = ['col1', 'col2', 'col3']
[data[h] for h in header] # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
If we zip them together, then we will get what we want:
zip(*(data[h] for h in header)) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
With that, we can write the data to the CSV file. Putting it all together:
import csv
data = {
'col1': [1, 2, 3],
'col2': [4, 5, 6],
'col3' : [7, 8, 9]
}
header = ['col1', 'col2', 'col3']
with open('dict_to_csv_in_order.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(zip(*(data[h] for h in header)))
Upvotes: 0
Reputation: 73480
Sth. like this should work:
import csv
d = {...}
with open('file.csv', 'wb') as f:
writer = csv.writer(f, delimiter=';')
header = ['col1', 'col2', 'col3']
# header = sorted(d.keys()[, key=custom_order_fnc])
rows = zip(*[d[col] for col in header])
writer.writerow(header)
for row in row:
writer.writerow(row)
Upvotes: 2