1

I have a list of python dictionaries that I'm trying to write the values into csv file, but for some reason I keep getting _csv.Error: sequence expected

Here is the sample code:

import csv
import os, sys

headers = ['id', 'Info']
data = [{'id': 1, 'Info': 'Example 1'}, {'id': 2, 'Info':'Example 2'}]

with open('all_csv.csv', 'wt') as f:
   writer = csv.writer(f, delimiter=',')
   writer.writerow(headers)
   for each in data:
      writer.writerow(each.values())

Any help would be appreciated.

1 Answer 1

1

in python 3, values() doesn't return a list anymore. You have to convert it first:

writer.writerow(list(each.values()))

note that dictionaries aren't ordered, so the order of the columns isn't defined (unless you're using Python 3.6 or higher), so maybe you want to use a csv.DictWriter object instead to avoid that your header doesn't match your rows.

Here's how I'd do it using csv.DictWriter:

import csv

data = [{'id': 1, 'Info': 'Example 1'}, {'id': 2, 'Info':'Example 2'}]

with open('all_csv.csv', 'w', newline="") as f:
   writer = csv.DictWriter(f, fieldnames = data[0], delimiter=',')
   writer.writeheader()
   writer.writerows(data)

the output is:

Info,id
Example 1,1
Example 2,2
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your amazing help. The header is in 9 columns, is there a way of simply defining the headers in a list? I noticed that my output has now jumbled up :(
passing headers as fieldnames should be ok too. But the fieldnames must match the keys exactly.
You are a life saver :)

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.