简体   繁体   中英

export dictionary to csv file in python

在此处输入图片说明

I am trying to export an output file as a CSV file.

I have 15 columns and 400 rows.

In my code, I stored data in the dictionary file, which means that I have one dictionary for each column.

So I want to get a CSV file which includes all dictionary in the same file.
I tried to use a (for) loop in order to do that, but it did not work.

use Pandas libray

let us Assume your dictionary is like this:

    my_dict = {'key1': '1', 'key2': 'b', 'key3': '123'}

To tackle your problem use :

    import pandas as pd

    (pd.DataFrame.from_dict(data=mydict, orient='columns')
    .to_csv('file_name.csv', header=False))

See Ivan Calderon's Answer for more information.!!

Please Check the variable as per your need. This should work.

def WriteCsv(csvFileName, csvFieldNames,  row=None ):

    import csv
    import os 
    if row:
        if os.path.exists(csvFileName):

            f_handle = open(csvFileName, 'a')
            csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
        else:

            f_handle =  open(csvFileName, 'w+')
            csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
            csvWriter.writeheader()
        try:
            csvWriter.writerow(row)
        finally:
            f_handle.close()

for row in dict_data:
    WriteCsv(csvFileName="Names.csv",csvFieldNames=csv_columns,row=row)

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