1

I'm trying to write a list into a csv file so that it's properly formatted. I've read from other stack overflow posts that below is the correct way to do so, (in order to preserve commas that I want to be printed out, etc), but this is just not working for me.

Rather than printing every list (within final_list) in its own csv row, it just prints one list per cell in one long, continuous line aka no line breaks. Any ideas on what I can do?

import csv 

final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerow(final_list)
1
  • Where is stats_dict defined? Commented Jan 12, 2016 at 6:08

3 Answers 3

1

You need to split your data into headers and then the rows (of data).

header = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

final_list = []

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open('output.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(header)
    writer.writerows(final_list) # note .writerows

# f.close() - not needed, the with statement closes the file for you
Sign up to request clarification or add additional context in comments.

Comments

0

I think you might be on Python 2.x but maybe this will help. I filled in a dummy stats_dict and rearranged the index of values (I call them v). I also made your final_list a list of lists.

final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]
stats_dict = {'Key': ['USA', 250000000, 75, 1000000, 1000001]}
for k, v in sorted(stats_dict.items()):
    if v[4] != 0:
        final_list.append([v[0], v[1], v[2], v[3], v[4]])

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerows(final_list)

Comments

0

Your code is almost spot on. You just need to see the difference between how final_list is evaluated in these two lines:

final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

and...

final_list.append([key, value[4], value[5], value[0], value[1]])

The first is a list of strings, the second is a list of lists. The second one is correct - each row in your CSV file is expected to be a list. To correct your code, make your first (header) row a list as well:

import csv 

# note that we have really only changed the next line
final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open("output.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(final_list) # we use writerows not writerow

2 Comments

Should be "w" instead of "wb" in your example since the list is strings, not bytes.
Well said, @Justin - updated.

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.