1

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))

1 Answer 1

1

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])])
Sign up to request clarification or add additional context in comments.

6 Comments

next error comes : csv_writer.writerow(x[y] for x in key) _csv.Error: sequence expected
@ErnaPiantari: again, add [...] brackets; a generator expression isn't supported, the result of a list comprehension is.
for csv_writer.writerow([x[y] for x in key]) my expected output is print string OFFENSE INVOLVING CHILDREN, But using my code , the output is only the first character O. Can you give me suggestion?
Why not just use csv_writer.writerow(key) instead? No need to loop there. You can write the value for each key with csv_writer.writerows(AllListInstance[key]).
AllListInstance.values() is frozen set. When I print csv_writer.writerow(key) the output is frozenset(['BATTERY', 'THEFT']). I want to split become BATTERY and THEAF and print to different coloum.
|

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.