Erna Piantari
Erna Piantari

Reputation: 627

Write to csv and I get error : _csv.Error: sequence expected

Please help. I get an error when I want to write my dict AllListInstance to csv file. This is my code:

AllListInstance= {frozenset(['OFFENSE INVOLVING CHILDREN']): [(95,), (96,), (35,), (80,), (100,)], frozenset(['BATTERY', 'THEFT']): [(173, 209), (173, 224)]}

with open('test1.csv', 'wb') as csv_file:
   for key in AllListInstance.keys():
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(len(AllListInstance[key]))
    for y in range(len(key)):
        csv_writer.writerow([x[y] for x in key])
        csv_writer.writerow(x[y] for x in AllListInstance[key])

output expected:

5   # len(AllListInstance["OFFENSE INVOLVING CHILDREN"]) count of member
OFFENSE INVOLVING CHILDREN
95
96
35
80
100
2 # len(AllListInstance['BATTERY','THIEF']) count of member
BATTERY        THIEF
173            209
173            224

Error:

    csv_writer.writerow(len(AllListInstance[key]))
_csv.Error: sequence expected

Solusion for my expected ouput:

with open('test8.csv', 'wb') as csv_file:
  for key in AllListInstance.keys():
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow([len(key),len(AllListInstance[key])])
    csv_writer.writerow(list(key))
    for x in AllListInstance[key]:
        csv_writer.writerow(list(x))

Upvotes: 1

Views: 3831

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123490

You are passing in a single integer:

len(AllListInstance[key])

That's not a sequence, which is what csv_writer.writerow() expects. If you want to write one column with the length value, wrap that in a list:

csv_writer.writerow([len(AllListInstance[key])])

Upvotes: 1

Related Questions