简体   繁体   中英

CSV to python list of dicts?

I looked through the questions already posted and my problems isn't quite solved. I think this should be fairly straight forward but I am getting tripped up with the variations. Hoping that after getting walked through this one file, then I can upload and parse the rest.

What I am trying to do:

  • File is open states data (and other files in dropbox ): ca_bills.csv
  • Convert .csv to python: I think it should be converted to a python list of dicts
  • Use the headers in the file as keys within dicts

I tried this but it didn't do what I wanted + I wonder if there is way to pull the fieldname from the headers of each file

    def csv_dict_writer(fp, fieldnames, data):
        with open(fp, "wb") as out_file:
        writer = csv.DictWriter(out_file, deliminter=',', fieldnames=fieldnames)
        writer.writeheader()
        for row in data:
            writer.writerow(row)

I also did this but this only prints and doesn't write to a file:

    with open('ca_bills.csv') as output_file:
        reader = csv.reader(output_file)
        for row in reader:
            print row

Thanks so much! This may be similar to other question but really couldn't extract what I needed. Appreciate your insights.

result=list(csv.DictReader(fp))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM