1

I'm trying to write a dictionary to csv file in python.

I'm using following solution:

Export a simple Dictionary into Excel file in python

However when i write to file in a following manner:

for key, value in dict1.iteritems():
    writer.writerow([key, value]) 

The key and the value from dictionary are stored in single column for each item in dictionary. I would like key to be stored in first column and value to be stored in second column and to assign headers to the columns if possible. Can anyone help?

5
  • 1
    Please show how you open the file and define writer. Is it identical to the linked question? Commented Oct 24, 2016 at 13:38
  • 1
    can you show a fragment of the result csv file? Commented Oct 24, 2016 at 13:44
  • Let me make sure I understand. You have just one dictionary with many items. You want to store it in two columns with the first column containing the keys and the second column containing the values, correct? Commented Oct 24, 2016 at 13:44
  • Further to my comment - I cannot replicate this issue. I think the possible errors are; you're defining a file extension other than .csv and Excel is opening it (I tried .xlsx but Excel says the file is corrupt so I'm not sure about this one) or you've defined writer to use a different delimiter e.g. ; which Excel is not configured to read, or you've changed the standard delimiter in Excel so that it isn't recognising ,. Commented Oct 24, 2016 at 13:53
  • Thank you for you're replies. It turned out that you were right! Excel was configured to use tab as a delimiter and not a comma! It works well after all. Commented Dec 8, 2016 at 11:31

1 Answer 1

1

You can do as follows using pandas :

import pandas as pd

dic = #your dictionnary
# Creating your dataframe from your dictionnary
df = pd.DataFrame([(k, v) for k, v in dic.iteritems()], columns=['key', 'value'])
# Store the data into a csv file
df.to_csv('your_path', sep=',') # indicate the path where to store the csv file
Sign up to request clarification or add additional context in comments.

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.