Python Forum
Need help to write dict to CSV
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help to write dict to CSV
#1
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:"
]
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 103,161 Apr-08-2020, 12:25 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020