Python Forum

Full Version: Need help to write dict to CSV
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I got a Dict, but I want to write to csv file using below command
How i can do it
Please advise.Thanks

writer = csv.DictWriter(csvfile, fieldnames=Csv_field)
writer.writerow({


{'Model:': 'Simplified', 'Asking:': '$545,000', 'Property Url:': 'https://www.srx.com.sg/listings/75818552/for-sale-lorong-8-toa-payoh-unblock-view-lor-8-market', 'PSF:': '$433 psf (Built-up)', 'HDB Town:': 'Toa Payoh'}
{'Model:': 'Simplified', 'Asking:': '$349,999', 'Built Year:': '1987', 'Property Url:': 'https://www.srx.com.sg/listings/75616032/for-sale-bukit-batok-street-34-good-price-4s-high-floor-blk349-bukit-batok', 'PSF:': '$387 psf (Built-up)', 'HDB Town:': 'Bukit Batok'}


Csv_field=[
"Model:",
"Asking:",
#"Property Name:",
#"Property Type:",
"Property Url:",
"Built Year:",
#"Address:",
"PSF:",
#"Area:",
#"Bedrooms:",
"HDB Town:"
]
Try this:

In [1]: import csv

In [2]: d = [{'one': 1, 'two': 2}, {'one': 'one', 'two': 'two'}]

In [3]: with open('test.csv', 'w') as csv_out:
   ...:     writer = csv.DictWriter(csv_out, d[0].keys()) # because you have a list of dicts just pick the first to get the keys
   ...:     writer.writeheader() # here it is where you write the header from the keys
   ...:     for dict_ in d: # 
   ...:         writer.writerow(dict_)
   ...:         

In [4]: cat test.csv # this is the Linux cat command which I use to display the file. Don't bother with it
one,two
1,2
one,two