0

I am writing a dictionary in a CSV file using this:

self.idSelf += 1
self.tweet["tweet"] = tweetText
self.tweet["id"] = id
self.tweet["sequence"] = self.idSelf
self.tweet["created_at"] = created_at
with open('#KXIPvMI-2018-05-04.csv', 'a') as csv_file:
     writer = csv.writer(csv_file)
     a = [self.tweet]
     print a[0]['tweet']
     writer.writerow([self.tweet])

While reading this file, I get a list of length = 1. I get the whole dictionary that I saved by writing row = info[0]. But when I get the type(row), it is str and not the dictionary. Why is that and how can I get the dictionary?

6
  • 3
    To write a dictionary, you should use csv.DictWriter. Commented May 5, 2018 at 5:31
  • Okay. And what would be the appropriate and pythonic way for that? Could you please post an answer with the snippet? Commented May 5, 2018 at 5:43
  • 1
    The answer is in the csv.DictWriter documentation. Commented May 5, 2018 at 5:45
  • @DyZ I am using DictWriter: writer = csv.DictWriter(csvfile, self.fieldnames=fieldnames) but I am getting an error: writer = csv.DictWriter(csv_file, fieldNames = self.fieldNames) TypeError: __init__() takes at least 3 arguments (2 given) Commented May 5, 2018 at 5:47
  • The error is likely coming from somewhere else. Look at the "official" example at docs.python.org/3/library/csv.html Commented May 5, 2018 at 5:50

1 Answer 1

1

Using csv.DictReader and csv.DictWriter, look at the sample code

import csv

di = {}
di["id"] = 1
di["val"] = "val"

with open("test.csv","a") as csv_file:
    writer = csv.DictWriter(csv_file,di.keys())
    writer.writerow(di)

with open("test.csv") as csv_file:
    reader = csv.DictReader(csv_file,di.keys())
    for row in reader:
        print row["id"]
Sign up to request clarification or add additional context in comments.

1 Comment

Using eval is not a good idea. Read about its potential threats. Instead you should use csv.DictReader

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.