Skip to content
Advertisement

How to create a custom CSV file from Python dictionary?

I want to create a CSV file like this:

Features, Value
f1, 1
f2, 2
f3, 3

But I get this:

f1, f2, f3
1, 2, 3

The code I wrote:

my_dict = {'f1': 1, 'f2': 2, 'f3': 3}
with open('testcsv.csv', 'w') as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

What should I do?

Advertisement

Answer

You would need to first transform your data according to the expected structure

data = [{'Features':i,'Value':my_dict[i]} for i in my_dict]

Once you do that you could use pandas to save it as CSV like so :

import pandas as pd
df = pd.DataFrame(data)
df.to_csv('testcsv.csv',index=None)

The resulting csv :

Features,Value
f1,1
f2,2
f3,3
Advertisement