0

enter image description here

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.

6
  • 2
    Please provide a Minimal, Complete, and Verifiable example Commented May 28, 2018 at 9:27
  • Add your peace of code Commented May 28, 2018 at 9:28
  • give DictWriter a read Commented May 28, 2018 at 9:30
  • can you post a sample format of your data? Commented May 28, 2018 at 9:33
  • What do you mean by 'one dictionary for each column' ? Each dictionary have one key for each row ? You can't use a list instead ? Commented May 28, 2018 at 9:36

2 Answers 2

1

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.!!

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.